mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
15.三数之和增加Go哈希解法
This commit is contained in:
@ -403,6 +403,7 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Go:
|
### Go:
|
||||||
|
(版本一) 双指针
|
||||||
|
|
||||||
```Go
|
```Go
|
||||||
func threeSum(nums []int) [][]int {
|
func threeSum(nums []int) [][]int {
|
||||||
@ -442,6 +443,42 @@ func threeSum(nums []int) [][]int {
|
|||||||
return res
|
return res
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
(版本二) 哈希解法
|
||||||
|
|
||||||
|
```Go
|
||||||
|
func threeSum(nums []int) [][]int {
|
||||||
|
res := make([][]int, 0)
|
||||||
|
sort.Ints(nums)
|
||||||
|
// 找出a + b + c = 0
|
||||||
|
// a = nums[i], b = nums[j], c = -(a + b)
|
||||||
|
for i := 0; i < len(nums); i++ {
|
||||||
|
// 排序之后如果第一个元素已经大于零,那么不可能凑成三元组
|
||||||
|
if nums[i] > 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
// 三元组元素a去重
|
||||||
|
if i > 0 && nums[i] == nums[i-1] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
set := make(map[int]struct{})
|
||||||
|
for j := i + 1; j < len(nums); j++ {
|
||||||
|
// 三元组元素b去重
|
||||||
|
if j > i + 2 && nums[j] == nums[j-1] && nums[j-1] == nums[j-2] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
c := -nums[i] - nums[j]
|
||||||
|
if _, ok := set[c]; ok {
|
||||||
|
res = append(res, []int{nums[i], nums[j], c})
|
||||||
|
// 三元组元素c去重
|
||||||
|
delete(set, c)
|
||||||
|
} else {
|
||||||
|
set[nums[j]] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### JavaScript:
|
### JavaScript:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user