您的位置:首页 > 编程语言 > C语言/C++

leetcode %15 in cpp

2016-05-21 05:52 447 查看
The solution first sorts the vector and then uses 2 pointer. For each number a, and its two pointer left and right( left starts at right next to a, and right starts at nums.size() - 1), if a + left  + right > sum, it means that the current sum should be
reduced, or right should be moved one step left; if a + left + right < sum, it means that the current sum should be increased, or left should be moved one step right. 

One of the trouble is how to avoid duplicates in the outputs. The solution is, whenever we move a, left or right, we should check if the next number is the same as the number we have checked previously. For a, each time we move from nums[i] to nums[i+1],
we check if nums[i] == nums[i+1]. If so then we move to nums[i+2] and check again. The same thing works for left and right.

code: 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());//sort the vector
int cur_sum;
int temp;

for(int i = 0; i < nums.size()-2; i ++){//if i == nums.size() -2, we have 2 numbers left to search and it is not possible to form a three sum. thus we terminate.
if(i-1 >= 0 && nums[i-1] == nums[i]) continue;//skipping the same number
cur_sum = -nums[i];
int left = i + 1; int right = nums.size() -1;
while(left < right){
temp = nums[left] + nums[right];
if(temp < cur_sum) left++;
else if(temp > cur_sum) right --;
else {
res.push_back(vector<int>{nums[i],nums[left],nums[right]});
while(left+1<nums.size() && nums[left] == nums[left+1]) left++;//skipping the same number to avoid duplicates in results
while(right-1>=0 && nums[right] == nums[right -1]) right--;//skipping the same number to avoid duplicates in results
left++;
right--;
}
}
}
return res;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp