LeetCode OJ:Three Sum(三数之和)

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

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • 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中的数first,再从剩下的数中取和等于 0 - first 的数即可。下面是代码(一开始没想出来,然后参考了别人的解法在写出来,一般的三层循环谁都能想到,但是时间复杂度太高,这里的这个时间复杂度应该是O(N^2),还是可以接受的)
 class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
vector<vector<int>> result;
int sz = nums.size();
sort(nums.begin(), nums.end());
for (int i = ; i < sz - ; ++i){
twoSum(nums, i + , - nums[i], result);
while(nums[i] == nums[i + ]) ++i;//这一步要注意,防止得出重复的vector
}
return result;
} void twoSum(vector<int> & nums, int start, int value, vector<vector<int>> & ret)
{
int beg = start;
int end = nums.size()-;
while (beg < end){
int sum = nums[beg] + nums[end];
if (sum < value)
beg++;
else if (sum > value)
end--;
else{
ret.push_back(vector<int>{nums[start - ], nums[beg], nums[end]});
while (nums[beg + ] == nums[beg]) beg++;//这一步的处理应该注意,防止出现相同的vector
while (nums[end - ] == nums[end]) end--;
beg++, end--;
}
}
}
};

java版的代码如下所示:

(由于不太熟悉ArrayList和List之间的关系,写起来感觉各种坑爹啊,注意下List和ArrayList之间的各种转换就可以了,代码如下):

 public class Solution {
List<List<Integer>> ret = new ArrayList<List<Integer>>(); public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; ++i){
twoSum(nums, i+1, 0 - nums[i]);
while(i < nums.length - 2 && nums[i] == nums[i+1])
++i;
}
return ret;
} public void twoSum(int[] nums, int start, int value)
{
int beg = start;
int end = nums.length - 1;
while(beg < end){
if(nums[beg] + nums[end] == value){
List<Integer> list = new ArrayList<Integer>();
list.add(nums[start - 1]);
list.add(nums[beg]);
list.add(nums[end]);
ret.add(list);
while(beg < end && nums[beg+1] == nums[beg])
beg++;
while(beg < end && nums[end-1] == nums[end])
end--;
beg++;
end--; }else if(nums[beg] + nums[end] > value){
end--;
}else{
beg++;
}
}
}
}

PS:同样的4Sum问题也可以转换成上面的3Sum问题,从而递归的求解,KSum问题也是一样

上一篇:LeetCode OJ:Path Sum II(路径和II)


下一篇:【iOS开发-52】假设要模仿练习,怎样找到其它应用程序的icon、使用框架等资源?