[LeetCode] 15. 三数之和

15. 三数之和

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

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

示例:

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

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

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/3sum

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

func threeSum(nums []int) [][]int {
	//先排序
	sort.Ints(nums)

	res := make([][]int, 0)
	f := func(nums []int, begin int, end int, target int) {
		for begin < end { //从两端向中间遍历
			if nums[begin]+nums[end]+target == 0 {
				r := make([]int, 0)
				r = append(r, nums[begin], nums[end], target)
				res = append(res, r)
				//遇到相等的,就快进
				for begin < end && nums[begin] == nums[begin+1] {
					begin++
				}
				for begin < end && nums[end] == nums[end-1] {
					end--
				}
				begin++
				end--
			} else if (target + nums[begin] + nums[end]) < 0 {
				begin++
			} else {
				end--
			}
		}
	}
	l := len(nums)
	for i := 0; i < l-2; i++ {
		if i > 0 && nums[i] == nums[i-1] {
			continue
		}
		f(nums, i+1, l-1, nums[i])
	}
	return res
}
func threeSum(nums []int) [][]int {
	n := len(nums)
	sort.Ints(nums)
	ans := make([][]int, 0)

	// 枚举 a
	for first := 0; first < n; first++ {
		// 需要和上一次枚举的数不相同
		if first > 0 && nums[first] == nums[first-1] {
			continue
		}
		// c 对应的指针初始指向数组的最右端
		third := n - 1
		target := -1 * nums[first]
		// 枚举 b
		for second := first + 1; second < n; second++ {
			// 需要和上一次枚举的数不相同
			if second > first+1 && nums[second] == nums[second-1] {
				continue
			}
			// 需要保证 b 的指针在 c 的指针的左侧
			for second < third && nums[second]+nums[third] > target {
				third--
			}
			// 如果指针重合,随着 b 后续的增加
			// 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
			if second == third {
				break
			}
			if nums[second]+nums[third] == target {
				ans = append(ans, []int{nums[first], nums[second], nums[third]})
			}
		}
	}
	return ans
}
posted @ 2020-06-12 15:40  翊仰  阅读(124)  评论(0编辑  收藏  举报