3Sum

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.

思路:

  双指针

他人代码:

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;
}
View Code

学习之处:

  • 双指针的形式主要有两种,第一种:一个在前,一个在后,可用于和后面的进行交换,第二种:一个在前,一个也在前。
  • 对于该问题虽然是3sum问题,我们可以通过一个个的控制元素不动,然后还剩余两个,这两个在游荡,使用双指针方法。
  • 问题中可以考虑的避免的重复计算很多如num[i] == num[i-1]不用考虑了,再如一旦匹配一个成功了num[left] = num[left+1]此种也不用考虑了。
原文地址:https://www.cnblogs.com/sunshisonghit/p/4335296.html