15. 3Sum

前端之家收集整理的这篇文章主要介绍了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,1,2,-1,-4],

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

找出一个数组中,和为0的三个元素的集合,且不能重复。

func threeSum(nums []int) [][]int {
    var results [][]int
    if len(nums) < 3 {
        return results
    }
    sort.Ints(nums)
    for i := 0; i < len(nums) && nums[i] <= 0; i++ {
        if i > 0 && nums[i] == nums[i-1] {
            continue
        }
        j := i + 1
        k := len(nums) - 1
        for j < k {
            sum := nums[i] + nums[j] + nums[k]
            if sum == 0 {
                results = append(results,[]int{nums[i],nums[j],nums[k]})
                for j < len(nums) - 1 && nums[j] == nums[j+1] {
                    j++
                }
                for k > 0 && nums[k] == nums[k-1] {
                    k--
                }
                j++
                k--
            } else if sum < 0 {
                j++
            } else if sum > 0 {
                k--
            }
        }
    }
    return results
}

猜你在找的Go相关文章