Leetcode-15 三数之和
原题链接 https://leetcode-cn.com/problems/3sum/
1 2
| func threeSum(nums []int) [][]int { }
|
题解
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
| func threeSum(nums []int) [][]int { sort.Ints(nums) var result [][]int
for i := 0; i < len(nums)-2; i++ { if nums[i] > 0 { break } if i > 0 && nums[i] == nums[i-1] { continue } j, k := i+1, len(nums)-1 for j < k { left, right := nums[j], nums[k] if nums[i]+nums[j]+nums[k] == 0 { result = append(result, []int{nums[i], nums[j], nums[k]}) for j < k && nums[j] == left { j++ } for j < k && nums[k] == right { k-- } } else if nums[i]+nums[j]+nums[k] < 0 { j++ } else { k-- } } } return result }
|
Github: https://github.com/Junedayday/code_reading
Blog: http://junes.tech/
Bilibili: https://space.bilibili.com/293775192
公众号: golangcoding