15. 3Sum

来源:互联网 发布:武汉市广电网络分公司 编辑:程序博客网 时间:2024/05/21 10:04

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

找出一个数组中,和为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}
0 0
原创粉丝点击