Commit d91ee0dc authored by yaozc's avatar yaozc
Browse files

keep going

parent d62e979c
// 1. Two Sum
// solution 1
// O(n^2)时间,double for loop
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int outer=0; outer<nums.size()-1; outer++){
vector<int> result;
result.push_back(outer);
int temp = target;
temp -= nums[outer];
for(int inner=outer+1; inner<nums.size(); inner++){
if(temp-nums[inner] == 0){
result.push_back(inner);
return result;
}
}
}
vector<int> result;
return result;
}
};
// solution 2
// O(n)时间,using hash table to find
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// first is the rest, second is the indice
unordered_map<int, int> hash;
for(int i=0; i<nums.size(); i++){
int rest = target - nums[i];
auto iter = hash.find(rest);
if (iter != hash.end()) {
std::vector<int> result;
result.push_back(i);
result.push_back(iter->second);
return result;
}
hash[nums[i]] = i;
}
std::vector<int> result;
return result;
}
};
//
// 2. Longest Substring Without Repeating Characters
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> hash;
int begin = 0;
hash[s[0]] = 0;
int max = 0;
for (size_t i = 1; i < count; i++) {
// if not found in hash or found but pos less than begin
if ( (hash.find(s[i]) == hash.end()) || (hash.find(s[i]) < begin)) {
}
else{
if (i - begin > max) {
max = i - begin;
}
begin = i;
}
hash[s[i]] = i;
}
if (i - begin > max) {
max = i - begin;
}
return max;
}
};
// 3. 3sum
// 用two sum的hash来做,容易产生duplicate的解,解决方案为sort一遍nums,然后用前后两个指针
// 来管理大小,同时要记得放过duplicate的数字,这里采用了upper_bound 和 lower_bound
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<std::vector<int>> result;
// sort the nums
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i) {
int target = -nums[i];
int front = i+1;
int back = nums.size()-1;
while (front < back) {
int sum = nums[front] + nums[back];
if (sum > target) {
back--;
}
else if (sum < target) {
front++;
}
else{
std::vector<int> temp_result;
temp_result.push_back(nums[i]);
temp_result.push_back(nums[front]);
temp_result.push_back(nums[back]);
result.push_back(temp_result);
front = std::upper_bound(nums.begin(), nums.end(), nums[front]) - nums.begin();
back = std::lower_bound(nums.begin(), nums.end(), nums[back]) - nums.begin()-1;
}
}
i = std::upper_bound(nums.begin(), nums.end(), nums[i]) - nums.begin();
}
return result;
}
};
// end
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment