LeetCode15

来源:互联网 发布:windows任务管理工具 编辑:程序博客网 时间:2024/05/23 21:53

【题目】

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.

【思路】

题目含义很简单,从一个数组中找出所有三个数的和为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,大佬所以为大佬

原创粉丝点击