加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

15. 3Sum

发布时间:2020-12-16 18:15:08 所属栏目:大数据 来源:网络整理
导读: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

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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读