Last active
June 28, 2019 15:35
-
-
Save yangpeng-chn/5ea0fa98ea3b561ea40797ed127242ab to your computer and use it in GitHub Desktop.
Two Pointers or Iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vector<vector<int>> threeSum(vector<int>& nums) { | |
vector<vector<int>> res; | |
if(nums.size() < 3) return res; | |
sort(nums.begin(), nums.end()); | |
for(int i = 0; i < nums.size()-2; i++){ | |
if (i > 0 && nums[i] == nums[i - 1]) continue; | |
int l = i+1; | |
int r = nums.size()-1; | |
int val = -nums[i]; | |
while(l < r){ | |
if(nums[l] + nums[r] > val) r--; | |
else if(nums[l] + nums[r] < val) l++; | |
else{ | |
res.push_back({nums[i], nums[l++], nums[r--]}); | |
while(l < r && nums[l] == nums[l-1]) l++; | |
while(l < r && nums[r] == nums[r+1]) r--; | |
} | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment