ethan

ethan

新知,热爱生活,码农,读书
twitter
email
github

LCR 15. Sum of Three Numbers

Given an integer array nums, determine whether there exists a triplet [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Please return all unique triplets that sum to 0.
Note: The answer should not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The unique triplets are [-1,0,1] and [-1,-1,2].
Note that the order of the output and the order of the triplets are not important.
Example 2:
Input: nums = [0,1,1]
Output: []
Explanation: There is no triplet that sums to 0.
Example 3:
Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only triplet that sums to 0 is [0,0,0].
Solution 1: Two Pointers

func threeSum(nums []int) (ans [][]int) {
    sort.Ints(nums)
    n := len(nums)
    for i, x := range nums[:n-2] {
        if i > 0 && x == nums[i-1] { // Skip duplicate numbers
            continue
        }
        if x+nums[i+1]+nums[i+2] > 0 { // Optimization 1
            break
        }
        if x+nums[n-2]+nums[n-1] < 0 { // Optimization 2
            continue
        }
        j, k := i+1, n-1
        for j < k {
            s := x + nums[j] + nums[k]
            if s > 0 {
                k--
            } else if s < 0 {
                j++
            } else {
                ans = append(ans, []int{x, nums[j], nums[k]})
                for j++; j < k && nums[j] == nums[j-1]; j++ {} // Skip duplicate numbers
                for k--; k > j && nums[k] == nums[k+1]; k-- {} // Skip duplicate numbers
            }
        }
    }
    return
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.