Commit d91ee0dc by yaozc

### keep going

parent d62e979c
amazon.cpp 0 → 100644
 // 1. Two Sum // solution 1 // O(n^2)时间，double for loop class Solution { public: vector twoSum(vector& nums, int target) { for(int outer=0; outer result; result.push_back(outer); int temp = target; temp -= nums[outer]; for(int inner=outer+1; inner result; return result; } }; // solution 2 // O(n)时间，using hash table to find class Solution { public: vector twoSum(vector& nums, int target) { // first is the rest, second is the indice unordered_map hash; for(int i=0; i result; result.push_back(i); result.push_back(iter->second); return result; } hash[nums[i]] = i; } std::vector result; return result; } }; //
bloomberg.cpp 0 → 100644
 // 2. Longest Substring Without Repeating Characters class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map 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> threeSum(vector& nums) { vector> 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 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