其他分享
首页 > 其他分享> > LeetCode 15 三数之和

LeetCode 15 三数之和

作者:互联网

问题描述

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

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

func threeSum(nums []int) [][]int {
	res2 := [][]int{}
	if len(nums) <3{
		return res2
	}
	Sort.Ints(nums)
	for i:=0; i<len(nums)-2; i++{
		n1 := nums[i]
                // 和为0必定存在负数,如果第一个数大于0,则和必定大于0
		if nums[i] > 0{
			break
		}
                // 去除重复数字
		if i >0 && nums[i] == nums[i-1]{
			continue
		}
		left, right := i+1, len(nums) - 1
		for left < right{
			n2, n3 := nums[left], nums[right]
                        // 和为0加入结果
			if n1 + n2 + n3 == 0 {
				res2 = append(res2, []int{n1, n2, n3})
                                // left, right移动且去重
				for left < right && nums[left] == n2{
					left ++
				}
				for left < right && nums[right] == n3{
					right --
				}
                        // 和小于0,所以left右移
			}else if n1 + n2 + n3 < 0{
				left ++
                        // 和大于0,所以right左移
			}else {
				right --
			}
		}
	}

	return res2
}

标签:right,15,nums,int,三数,n2,n3,LeetCode,left
来源: https://blog.csdn.net/weixin_42505583/article/details/118684137