Skip to content

15. 3Sum

Jacky Zhang edited this page Oct 31, 2016 · 2 revisions

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: 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]
]

Array类题目。

这道题的关键点是如何避免"Time Limit Exceeded"。 可先将Arra排序,然后先选定一个数,剩下两个数可以在后面的两端开始取。 注意需跳过重复的数。

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums.length < 3) return res;
        Arrays.sort(nums);
        for(int i = 0; i < nums.length-2; i++) {
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int target = -nums[i];
            int j = i+1, k = nums.length-1;
            while(j < k) {
                if(j > i+1 && nums[j] == nums[j-1]) {
                    j++;
                    continue;
                }
                if(k < nums.length-1 && nums[k] == nums[k+1]) {
                    k--;
                    continue;
                }
                int sum = nums[j] + nums[k];
                if(sum == target) {
                    res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    j++;
                    k--;
                } else if(sum > target) {
                    k--;
                } else {
                    j++;
                }
            }
        }
        return res;
    }
}
Clone this wiki locally