Commit 6c8075fe by yaozc

### keep going

parent 96fd819e
No preview for this file type
This diff is collapsed.
 // 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
No preview for this file type
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!