15. 3Sum

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

Solution:Two pointers

因为要去重,所以用TwoPointers instead of hashmap
如果是返回位置index的话,排序+two pointers 位置改变了 还需要原序列上找 index,不如用hashmap
思路:排序后,�for every element, two pointers to find other two, with skipping process
Time Complexity: O(N^2) Space Complexity: O(1)

Solution Code:

class Solution {
    public List> threeSum(int[] nums) {
        List> result = new ArrayList>();
        if(nums == null || nums.length == 0) return result;
        Arrays.sort(nums);
        
        if (3 * nums[0] > 0 || 3 * nums[nums.length - 1] < 0)  // early not found
            return result;
        
        for(int i = 0; i < nums.length - 2; i++) {
            if(i != 0 && nums[i] == nums[i - 1]) continue; //skip num1 dup 
            int target = -nums[i];
            
            // two pointers
            int start = i + 1, end = nums.length - 1;
            while(start < end) {
                if(nums[start] + nums[end] == target) { 
                    result.add(Arrays.asList(nums[i], nums[start], nums[end]));
                    while(start < end && nums[start] == nums[start + 1]) start++;  // skip num2 dup 
                    while(start < end && nums[end] == nums[end - 1]) end--;    // skip num3 dup 
                    start++; 
                    end--;
                }
                else if(nums[start] + nums[end] < target) {
                    start++;
                }
                else {
                    end--;
                }
            }
        }
        return result;
    }
}

你可能感兴趣的:(15. 3Sum)