Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Last active June 28, 2019 15:35
Show Gist options
  • Save yangpeng-chn/5ea0fa98ea3b561ea40797ed127242ab to your computer and use it in GitHub Desktop.
Save yangpeng-chn/5ea0fa98ea3b561ea40797ed127242ab to your computer and use it in GitHub Desktop.
Two Pointers or Iterators
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