LeetCoder 解题报告 3Sum

来源:互联网 发布:永诚网络 编辑:程序博客网 时间:2024/05/22 10:47

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)
题意:给定一个数组,找出其中的三个数,使之三个数的和为0,并输出这三个数,按从小到大输出,如果有多组就全部输出。

分析:在 LeetCode 解题报告 Two Sum 这篇文章中介绍了三种方法,此题是这个题的升级版,这个题如果用暴力解决那么将是O(n3)的时间复杂度,如果用HashMap也是不方便,因为数据是可重复的。

接下来就直接看代码

public List<List<Integer>> threeSum(int[] num) {        Arrays.sort(num);        List<List<Integer>> list = new ArrayList<List<Integer>> ();        int first, end, mid;        //遍历数组        for(int i = 0; i < num.length-2; i++) {        if(i==0 || num[i] > num[i-1]) {        first = i;        end = num.length - 1;        mid = first + 1;        if(num[first] > 0 || num[end] < 0)        break;        while(mid < end) {        int sum = num[first] + num[mid] + num[end];        if(sum == 0) {        ArrayList<Integer> each = new ArrayList<Integer>();        each.add(num[first]);        each.add(num[mid]);        each.add(num[end]);        if(!list.contains(each))        list.add(each);        mid++;        end--;        while(mid < end && num[end] == num[end-1])        end--;        while(mid < end && num[mid] == num[mid+1])        mid ++;        }        else if(sum < 0) {        mid++;        }        else         end--;        }        }        }        return list;    }

思路其实就很简单了,就是锁定第一个值遍历,剩下的两个的数,按照数组中寻找两个数的和是定值来解决就ok了。

如果按着思路写出的代码提交会有出现超时现象,那么我们就要优化了。

这里面做了很多的优化,比如:

if(i==0 || num[i] > num[i-1])
这里是防止相同数据输入

while(mid < end && num[end] == num[end-1])        end--;        while(mid < end && num[mid] == num[mid+1])        mid ++;
这里避免不必要的重复








0 0