题解 | #三数之和#

三数之和

https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711

go golang 三个for嵌套,每个for都要去重(考虑-1 -1 -1 1 1 1的情况)。

先确定a,再确定b,则确定target=0-a-b,那么只要找到c == target,便找到一组答案a,b,c。

package main

import "sort"

/**
 *
 * @param num int整型一维数组
 * @return int整型二维数组
 */
// 2023-03-14
func threeSum(num []int) [][]int {
	// write code here
	if len(num) < 3 {
		return [][]int{}
	}
	sort.Ints(num)
	res := [][]int{}
	for a := 0; a < len(num)-2; a++ {
        if a > 0 && num[a] == num[a-1] {
            continue
        }
        for b := a+1; b < len(num)-1; b++ {
            if b > a+1 && num[b] == num[b-1] {
                continue
            }
            target := -num[a]-num[b]
            for c := b+1; c < len(num); c++ {
                if c > b+1 && num[c] == num[c-1] {
                continue
                }
                if num[c] == target {
                    res = append(res, []int{num[a],num[b],num[c]})
                }
            }
        }
	}
	return res
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务