您的位置:首页 > 编程语言 > Java开发

LeetCode15 - 3Sum

2017-07-14 10:56 387 查看
【题目】

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

【思路】

题目含义很简单,从一个数组中找出所有三个数的和为0的组合,在一个组合中,一个数不能重复用,组合不能重复

我的思路很简单,先将数组排序,然后两个两个为一组,在之后的数组中,二分查找找出满足和为0的数,时间复杂度为O(n*n*logn),结果果然排在了比较靠后的位置。

【Java代码】

public class Solution_15_3Sum {
public List<List<Integer>> threeSum(int[] nums){
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i = 0 ; i < nums.length-2 ; i++){
if(i > 0 && nums[i] == nums[i-1])
continue;
for(int j = i+1; j < nums.length-1 ; j++){
if(j > i+1 && nums[j] == nums[j - 1])
continue;
if(Arrays.binarySearch(nums,j+1,nums.length,0-nums[i]-nums[j])>=0)
result.add(Arrays.asList(nums[i],nums[j],0-nums[i]-nums[j]));
}
}
return result;
}
}【大佬】
所以必须膜拜了大佬们的思路,复杂度为O(n)。

先对数组排序, 从头到尾逐个遍历数组中的元素,对于每一个元素,计算后边剩下的部分能不能找出两个数的和,满足与该元素相加为0。

在寻找两数之和时,分别从首尾向中间遍历,若两数相加小了,则左侧右移,反之则右侧左移。

public List<List<Integer>> threeSum(int[] num) {
Arrays.sort(num);
List<List<Integer>> res = new LinkedList<>();
for (int i = 0; i < num.length-2; i++) {
if (i == 0 || (i > 0 && num[i] != num[i-1])) {
int lo = i+1, hi = num.length-1, sum = 0 - num[i];
while (lo < hi) {
if (num[lo] + num[hi] == sum) {
res.add(Arrays.asList(num[i], num[lo], num[hi]));
while (lo < hi && num[lo] == num[lo+1]) lo++;
while (lo < hi && num[hi] == num[hi-1]) hi--;
lo++; hi--;
} else if (num[lo] + num[hi] < sum) lo++;
else hi--;
}
}
}
return res;
}

【提高】
以上代码运行之后可以排在中间位置,而最好的代码与其思路基本相同,唯一区别,是在选定第一个元素时,判断其是否>0,若大于0,则直接返回当前结果。。。。6666,大佬所以为大佬
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Java