github.com/qiuhoude/go-web@v0.0.0-20220223060959-ab545e78f20d/algorithm/leetcode/3sum_test.go (about) 1 package leetcode 2 3 import ( 4 "sort" 5 ) 6 7 // 15. 三数之和 https://leetcode-cn.com/problems/3sum/ 8 9 /* 10 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。 11 12 例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4], 13 14 满足要求的三元组集合为: 15 [ 16 [-1, 0, 1], 17 [-1, -1, 2] 18 ] 19 */ 20 func threeSum(nums []int) [][]int { 21 // 思路: 1.排序, 22 // 2. 使用三指针 i l r 23 24 sort.Slice(nums, func(i, j int) bool { 25 return nums[i] < nums[j] // 正序 26 }) 27 28 var res [][]int 29 length := len(nums) 30 if length < 3 || nums[0] > 0 { 31 // 无解情况 32 return nil 33 } 34 35 for i := 0; i < length && nums[i] <= 0; i++ { 36 l := i + 1 37 r := length - 1 38 if i > 0 && nums[i] == nums[i-1] { // 重复的去掉 39 continue 40 } 41 for l < r { 42 sum := nums[i] + nums[l] + nums[r] 43 if sum == 0 { // 找到目的 44 res = append(res, []int{nums[i], nums[l], nums[r]}) 45 for l < r && nums[l] == nums[l+1] { // 去重 46 l++ 47 } 48 for l < r && nums[r] == nums[r-1] { // 去重 49 r-- 50 } 51 l++ 52 r-- 53 } else if sum < 0 { 54 l++ 55 } else if sum > 0 { 56 r-- 57 } 58 } 59 } 60 61 return res 62 }