Leetcode#15 3Sum
Published:
Link:
https://leetcode.com/problems/3sum/description/
Idea:
Need to skip same target to exclude duplicated sum target.
Solution:
class Solution {
public:
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(); i++) {
/* exclude duplicated target */
if (i > 0 && nums[i] == nums[i-1])
continue;
int target = 0 - nums[i];
int left = i+1;
int right = nums.size()-1;
while (left < right) {
if (target == nums[left] + nums[right]) {
vector<int> ans;
ans.push_back(nums[i]);
ans.push_back(nums[left]);
ans.push_back(nums[right]);
res.push_back(ans);
left++;
right--;
while (left < nums.size() && nums[left] == nums[left-1])
left++;
while (right > 0 && nums[right] == nums[right+1])
right--;
} else {
if (target > nums[left] + nums[right]) {
left++;
} else {
right--;
}
}
}
}
return res;
}
};