LeetCode OJ

题目:

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)

解题思路:

  先将数组排序。 然后分别固定第一个元素为num[0], num[n]。 用2Sum的方法找剩下的两个数。

代码:

 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
 3         Arrays.sort(num);
 4         ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
 5         for (int first = 0; first < num.length;) {
 6             int left = first + 1, right = num.length - 1;
 7             while (left < right) {
 8                 int sum = num[first] + num[left] + num[right];
 9                 if (sum == 0) {
10                     ArrayList<Integer> cur_ans = new ArrayList<Integer>();
11                     cur_ans.add(num[first]); cur_ans.add(num[left]); cur_ans.add(num[right]);
12                     ans.add(cur_ans);
13                     left++; right--;
14                 } else if (sum > 0) {
15                     right --;
16                 } else {
17                     left ++;
18                 }
19                 while (left < right && (left != first+1 && num[left] == num[left-1])) left ++; // delete duplicate triplets
20                 while (left < right && (right != num.length-1 && num[right] == num[right+1])) right --;// delete duplicate triplets
21             }
22             for (first++; first < num.length && num[first] == num[first-1]; first ++);// delete duplicate triplets
23         }
24         return ans;
25     }
26 }
原文地址:https://www.cnblogs.com/dongguangqing/p/3788790.html