lvpengbo

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

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

func threeSum(nums []int) [][]int {
	sort.Ints(nums)
	res := [][]int{}

	for i := 0; i < len(nums)-2; i++ {
		n1 := nums[i]
		if n1 > 0 {
			break
		}
		if i > 0 && n1 == nums[i-1] {
			continue
		}
		l, r := i+1, len(nums)-1
		for l < r {
			n2, n3 := nums[l], nums[r]
			if n1+n2+n3 == 0 {
				res = append(res, []int{n1, n2, n3})
				for l < r && nums[l] == n2 {
					l++
				}
				for l < r && nums[r] == n3 {
					r--
				}
			} else if n1+n2+n3 < 0 {
				l++
			} else {
				r--
			}
		}
	}
	return res
}

  

分类:

技术点:

相关文章:

  • 2021-11-17
  • 2022-12-23
  • 2022-03-04
  • 2021-04-21
  • 2021-03-31
  • 2021-04-14
  • 2021-08-16
猜你喜欢
  • 2021-07-05
  • 2021-11-25
  • 2021-12-28
  • 2022-03-12
  • 2022-12-23
  • 2022-01-10
相关资源
相似解决方案