1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// @Title: 三数之和 (3Sum)
// @Author: 15816537946@163.com
// @Date: 2020-10-29 15:01:14
// @Runtime: 44 ms
// @Memory: 7.4 MB
func threeSum(nums []int) [][]int {
	nLen := len(nums)
	if nLen < 3 {
		return nil
	}

	res := make([][]int, 0, len(nums))
	sort.Ints(nums)

	for i := range nums {
		// 解决相同的边界问题
		if i > 0 && nums[i] == nums[i-1] {
			continue
		}

		lo, hi := i+1, nLen-1 // 初始化指针
		for lo < hi {
			sum := nums[i] + nums[lo] + nums[hi]
			if sum == 0 {
				res = append(res, []int{nums[i], nums[lo], nums[hi]})

				for lo < hi && nums[lo] == nums[lo+1] {
					lo++
				}
				for lo < hi && nums[hi] == nums[hi-1] {
					hi--
				}
				lo++
				hi--
			} else if sum > 0 {
				hi--
			} else {
				lo++
			}
		}
	}
	return res

}