求和问题 添加Go语言代码
parent
8d552eb9d4
commit
7f4947f527
|
@ -167,3 +167,50 @@ class Solution {
|
|||
}
|
||||
```
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func threeSum(nums []int) [][]int {
|
||||
res := [][]int{}
|
||||
length := len(nums)
|
||||
if length < 3 {
|
||||
return res
|
||||
}
|
||||
|
||||
sort.Ints(nums)
|
||||
for i := 0; i < length - 2; i++ {
|
||||
// 去重
|
||||
if i != 0 && nums[i] == nums[i - 1] {
|
||||
continue
|
||||
}
|
||||
l, r := i + 1, length - 1
|
||||
for l < r {
|
||||
/*
|
||||
// 下面两个for循环的去重也可以用下面的代码替换
|
||||
if l != i + 1 && nums[l] == nums[l - 1] {
|
||||
l++
|
||||
continue
|
||||
}
|
||||
*/
|
||||
if nums[i] + nums[l] + nums[r] == 0 {
|
||||
res = append(res, []int{nums[i], nums[l], nums[r]})
|
||||
for l < r && nums[l] == nums[l + 1] {
|
||||
l++
|
||||
}
|
||||
for l < r && nums[r] == nums[r - 1] {
|
||||
r--
|
||||
}
|
||||
l++
|
||||
r--
|
||||
} else if nums[i] + nums[l] + nums[r] < 0 {
|
||||
l++
|
||||
} else {
|
||||
r--
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
|
|
|
@ -54,6 +54,21 @@ class Solution {
|
|||
}
|
||||
```
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func twoSum(nums []int, target int) []int {
|
||||
m := make(map[int]int)
|
||||
for i, num := range nums {
|
||||
if v, ok := m[target - num]; ok {
|
||||
return []int{v, i}
|
||||
}
|
||||
m[num] = i
|
||||
}
|
||||
return []int{}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### 双指针(暴力)法
|
||||
|
|
|
@ -96,7 +96,59 @@ class Solution {
|
|||
}
|
||||
```
|
||||
|
||||
|
||||
Go Code:
|
||||
|
||||
```go
|
||||
func fourSum(nums []int, target int) [][]int {
|
||||
res := [][]int{}
|
||||
length := len(nums)
|
||||
if length < 4 {
|
||||
return res
|
||||
}
|
||||
|
||||
sort.Ints(nums)
|
||||
for i := 0; i < length - 3; i++ {
|
||||
// 去重
|
||||
if i != 0 && nums[i] == nums[i - 1] {
|
||||
continue
|
||||
}
|
||||
for j := i + 1; j < length - 2; j++ {
|
||||
// 去重
|
||||
if j != i + 1 && nums[j] == nums[j - 1] {
|
||||
continue
|
||||
}
|
||||
l, r := j + 1, length - 1
|
||||
for l < r {
|
||||
/*
|
||||
// 下面两个for循环的去重也可以用下面的代码替换
|
||||
if l != i + 1 && nums[l] == nums[l - 1] {
|
||||
l++
|
||||
continue
|
||||
}
|
||||
*/
|
||||
sum := nums[i] + nums[j] + nums[l] + nums[r]
|
||||
if sum == target {
|
||||
res = append(res, []int{nums[i], nums[j], nums[l], nums[r]})
|
||||
for l < r && nums[l] == nums[l + 1] {
|
||||
l++
|
||||
}
|
||||
for l < r && nums[r] == nums[r - 1] {
|
||||
r--
|
||||
}
|
||||
l++
|
||||
r--
|
||||
} else if sum < target {
|
||||
l++
|
||||
} else {
|
||||
r--
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
|
Loading…
Reference in New Issue