求和问题 添加Go语言代码

pull/43/head
zouxinyao 2021-07-25 13:40:47 +08:00
parent 8d552eb9d4
commit 7f4947f527
3 changed files with 115 additions and 1 deletions

View File

@ -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
}
```

View File

@ -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{}
}
```
###

View File

@ -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
}
```