015-三数之和 3Sum

Description

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

Note

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

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

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
Solution
func threeSum(nums []int) [][]int {
    return threeSum1(nums,0)
}

func sortNums(nums []int)  {
    for i := 0;i < len(nums);i ++ {
        for j := i +1 ; j < len(nums);j ++ {
            if nums[i] > nums[j] {
                nums[i],nums[j] = nums[j],nums[i]
            }
        }
    }
}

func threeSum1(nums []int ,target int) [][]int {
    sortNums(nums)
    var list [][]int
    maps := make(map[int]int,len(nums))
    for i,v := range nums{
        maps[v] = i
    }
    valuess := make([]int,3)
    maps2 := map[string]bool{}
    for i := 0 ; i < len(nums); i ++ {
        if nums[i] > target {
            break
        }
        for j := i + 1; j < len(nums); j ++ {
            member := target - nums[i] - nums[j]
            if k,ok := maps[member];ok && k != i && k != j {
                valuess = []int{member,nums[i],nums[j]}
                sortNums(valuess)
                key := fmt.Sprintf("%d%d%d",valuess[0],valuess[1],valuess[2])
                if _,ok := maps2[key];ok {
                    continue
                }else {
                    maps2[key] = true
                    list = append(list, []int{valuess[0],valuess[1],valuess[2]})
                }
            }
        }
    }
    return list
}

leetCode地址