mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-18 11:52:19 +00:00
添加Go语言题解
This commit is contained in:
@@ -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
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user