您的位置:首页 > 其它

Leetcode 15. 3Sum

2018-01-30 09:56 134 查看
原题:

Given an array S of n integers, are there elements a,b,c inS such that
a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]


解决方法:
解决这道题,首先想到的是需要对数组进行排序,然后先固定一个数,在剩下的数进行查找符合要求的其他两个数。

特别需要留意的是不需要重复结果,所有要跳过所有的重复数。

代码:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int n = nums.size();

// 在排序数组中查找更加方便
sort(nums.begin(), nums.end());

for(int i = 0; i < n - 2; i++){
// 最小的数肯定得是负数,否则和不可能为0
if (nums[i] > 0)
break;

int target = -nums[i];
int lo = i+1, hi = n -1;

while(lo < hi){
int sum = nums[lo] + nums[hi];
if (sum == target){
vector<int> ans;
ans.push_back(nums[i]);
ans.push_back(nums[lo]);
ans.push_back(nums[hi]);
res.push_back(ans);

// 跳过重复数
while( nums[lo] == ans[1])
++lo;

// 跳过重复数
while(nums[hi] == ans[2])
--hi;
}else if (sum < target){
++lo;
}else{
--hi;
}
}

// 跳过重复数
while( i + 1 < n && nums[i+1] == nums[i])
++i;
}

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