[leetcode]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.

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)

思路1:
与之前的[leetcode]Two Sum的思路1相似,加一层外循环。时间复杂度为O(n^3)
思路2:
与之前的[leetcode]Two Sum的思路1相似,加一层外循环。时间复杂度为O(n^2),思路完全一样,大家可以自己实现一下。
思路3:
先对整个数组进行排序,外层循环对每个元素i(i < length - 2)进行遍历,然后在余下的元素(i + 1 ~ length)中采用双指针进行检索,参考原博文[leetcode]3Sum 的讲解
代码如下:
 1 public class Solution {
 2     public List<List<Integer>> threeSum(int[] num) {
 3         List<List<Integer>> result = new ArrayList<List<Integer>>();
 4         if(num == null || num.length < 3) return result;
 5         Arrays.sort(num);
 6         for(int i = 0; i < num.length; i++){
 7             if(i > 0 && num[i] == num[i - 1]) continue;
 8             int begin = i + 1;
 9             int end = num.length - 1;
10             while(begin < end){
11                 if(num[begin] + num[end] + num[i] == 0){
12                     List<Integer> list = new ArrayList<Integer>();
13                     list.add(num[i]);
14                     list.add(num[begin]);
15                     list.add(num[end]);
16                     result.add(list);
17                     begin++;
18                     end--;
19                     while(begin < end && num[begin] == num[begin - 1]) begin++;
20                     while(end > i && num[end] == num[end + 1]) end--;
21                 }else if(num[begin] + num[end] + num[i] > 0){
22                     end--;
23                 }else{
24                     begin++;
25                 }
26             }
27         }
28         return result;
29     }
30 }



 

原文地址:https://www.cnblogs.com/huntfor/p/3841654.html