3Sum

来源:互联网 发布:中国进出口总额数据 编辑:程序博客网 时间:2024/06/08 14:32

3Sum

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)
Java代码:

public class Solution {    public List<List<Integer>> threeSum(int[] num) {       if (num == null) return null;    List<List<Integer>> result = new ArrayList<List<Integer>>();    int len = num.length;    // Sort    Arrays.sort(num);    for (int i=0; i<len-2; i++) {        for (int j=i+1; j<len-1; j++) {            for (int k=j+1; k<len; k++) {                if (num[i] + num[j] + num[k] == 0) {                    // Save result                    List<Integer> l = new ArrayList<Integer>();                    l.add(num[i]); l.add(num[j]); l.add(num[k]);                    result.add(l);                    // Bypass second and third elements                    int K = k;                    while (k<len && num[k++] == num[K]);                    k = k == len ? k : k-2;                    int J = j;                    while (j<len-1 && num[j++] == num[J]);                    j = j == len-1 ? j : j-2;                }            }        }        // Bypass first element        int I = i;        while (i<len-2 && num[i++] == num[I]);        i = i == len-2 ? i : i-2;    }    return result;     }}


0 0
原创粉丝点击