LeetCode #15 3Sum (M)

[Problem]

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)

[Analysis]

这题的要点是Note里面的两个要求,这个可以通过排序解决。排序之后先提出一个数字再用2Sum解决即可。需要注意的是跳过已经用过的数字。总体复杂度是O(nlogn) + O(n*n) = O(n*n)。

 

[Solution]

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Solution {
    public List<List<Integer>> threeSum(int[] num) {
        List<List<Integer>> solution = new ArrayList<List<Integer>>();
        if (num.length < 3) {
            return solution;
        }
        
        Arrays.sort(num);
        
        int target = 0;
        for (int i = 0; i < num.length - 2; i++) {
            if (i > 0 && num[i] == num[i - 1]) {
                continue; // if current value is already tested as the first element, skip; 
            }
            
            // Do 2Sum
            int head = i + 1;
            int tail = num.length - 1;
            
            while (head < tail) {
                if (head > i + 1 && num[head] == num[head - 1]) {
                    head++;
                    continue; // if current value is already tested as the second, skip;
                }
                
                if (tail < num.length - 1 && num[tail] == num[tail + 1]) {
                    tail--;
                    continue; // similar test for the third element
                }
                
                int sum = num[i] + num[head] + num[tail];
                if (sum == target) {
                    solution.add(new ArrayList<Integer>(Arrays.asList(num[i], num[head], num[tail])));
                    head++;
                    tail--;
                } else if (sum > target) {
                    tail--;
                } else {
                    head++;
                }
            }
        }
        
        return solution;
    }
}

 

posted on 2015-10-09 22:49  张惬意  阅读(160)  评论(0编辑  收藏  举报