leetcode三数相加为零

题目:

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

python代码

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) < 3:
            return
        nums.sort()
        if nums[0] > 0:
            return
        from collections import defaultdict
        res = []
        d = defaultdict(int)
        for i in nums:
            d[i] += 1

        if d[0] > 2:
            res.append([0, 0, 0])
        list1 = sorted(set(filter(lambda x: x > 0, nums)))
        list2 = sorted(set(filter(lambda x: x < 0, nums)))
        for i in list1:
            for j in list2:
                temp = -(i + j)
                if d[temp] > 0:
                    if temp == i and d[temp] > 1:
                        res.append([i, j, temp])
                    elif temp == j and d[temp] > 1:
                        res.append([i, j, temp])
                    elif temp > i or temp < j or temp == 0:
                        res.append([i, j, temp])
        return res

golang代码

func threeSum(nums []int) [][]int {
	res := [][]int{}
	maps := make(map[int]int)
	for _, num := range nums {
		if maps[num] > 0 {
			maps[num] += 1
		} else {
			maps[num] = 1
		}
	}
	if maps[0] > 2 {
		res = append(res, []int{0, 0, 0})
	}
	nums1 := []int{}
	nums2 := []int{}
	for num := range maps {
		if num > 0 {
			nums1 = append(nums1, num)
		} else if num < 0 {
			nums2 = append(nums2, num)
		}
	}

	for _, a := range nums1 {
		for _, b := range nums2 {
			c := 0 - a - b
			if maps[c] > 0 {
				if c == a && maps[c] > 1 {
					res = append(res, []int{a, b, c})
				} else if c == b && maps[c] > 1 {
					res = append(res, []int{a, b, c})
				} else if c > a || c < b || c == 0 {
					res = append(res, []int{a, b, c})
				}
			}
		}
	}
	return res
}
posted @ 2019-07-09 20:16  村口王铁匠  阅读(197)  评论(0)    收藏  举报