[LC] 15. 3Sum

Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Time: O(N^2)
 1 class Solution:
 2     def threeSum(self, nums: List[int]) -> List[List[int]]:
 3         res = []
 4         if nums is None:
 5             return res
 6         
 7         nums.sort()
 8         for i in range(len(nums) - 2):
 9             if i > 0 and nums[i] == nums[i - 1]:
10                 continue
11             target = -nums[i]
12             left = i + 1
13             right = len(nums) - 1
14             while left < right:
15                 if nums[left] + nums[right] == target:
16                     lst = [nums[i], nums[left], nums[right]]
17                     res.append(lst)
18                     left += 1
19                     right -= 1
20                     while left < right and nums[left] == nums[left - 1]:
21                         left += 1
22                     while left < right and nums[right] == nums[right + 1]:
23                         right -= 1
24                 elif nums[left] + nums[right] < target:
25                     left += 1
26                 else:
27                     right -= 1
28         return res
29         
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            // skip i as well
            if (i > 0 && nums[i - 1] == nums[i]) {
                continue;
            }
            int j = i + 1, k = nums.length - 1;
            // j and k cannot meet since may add the same number twice
            while (j < k) {
                int target = nums[i] + nums[j] + nums[k];
                if (target == 0) {
                    res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    j += 1;
                    while (j < k && nums[j] == nums[j - 1]) {
                        j += 1;
                    }
                } else if (target < 0) {
                    j += 1;
                } else {
                    k -= 1;
                }
            }
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/xuanlu/p/11652420.html