添加Go语言题解

This commit is contained in:
zouxinyao
2021-07-28 02:26:32 +08:00
parent 7eb8b4a9fd
commit 575b7612f0
52 changed files with 1679 additions and 104 deletions

View File

@@ -162,3 +162,52 @@ 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

@@ -95,3 +95,61 @@ 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
}
```