首页 > 代码库 > 3Sum Leetcode

3Sum Leetcode

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: 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]
]
这道题思路会了就很好写。。。但是我一开始总是执着于两边加和然后从中间找第三个值。。。
可以试着反思路。。。经典题目,回顾一下吧。
学习一下Arrays.asList()的用法。
public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return result;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if (nums[i] > 0) {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int start = i + 1;
            int end = nums.length - 1;
            int target = 0 - nums[i];
            while (start < end) {
                int tmp = nums[start] + nums[end];
                if (tmp > target){
                    end--;
                } else if (tmp < target) {
                    start++;
                } else {
                    result.add(Arrays.asList(nums[i], nums[start], nums[end]));
                    while (start < end && nums[start] == nums[start + 1]) {
                        start++;
                    }
                    while (start < end && nums[end] == nums[end - 1]) {
                        end--;
                    }
                    start++;
                    end--;
                }
            }
        }
        return result;
    }
}

 

3Sum Leetcode