-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18.4sum.go
109 lines (94 loc) · 1.86 KB
/
18.4sum.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// package main
import (
"sort"
)
/*
* @lc app=leetcode id=18 lang=golang
*
* [18] 4Sum
*
* https://leetcode.com/problems/4sum/description/
*
* algorithms
* Medium (29.22%)
* Total Accepted: 208.2K
* Total Submissions: 705.4K
* Testcase Example: '[1,0,-1,0,-2,2]\n0'
*
* Given an array nums of n integers and an integer target, are there elements
* a, b, c, and d in nums such that a + b + c + d = target? Find all unique
* quadruplets in the array which gives the sum of target.
*
* Note:
*
* The solution set must not contain duplicate quadruplets.
*
* Example:
*
*
* Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
*
* A solution set is:
* [
* [-1, 0, 0, 1],
* [-2, -1, 1, 2],
* [-2, 0, 0, 2]
* ]
*
*
*/
func fourSum(nums []int, target int) [][]int {
sort.Ints(nums)
solutions := [][]int{}
l := len(nums)
for i := 0; i <= l-4; i++ {
if nums[i] > 0 && nums[i] > target {
break
}
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j := i + 1; j <= l-3; j++ {
if nums[i]+nums[j] > 0 && nums[i]+nums[j] > target {
break
}
if j > i+1 && nums[j] == nums[j-1] {
continue
}
k := j + 1
m := l - 1
for k < m {
sum := nums[i] + nums[j] + nums[k] + nums[m]
if k > j+1 && nums[k] == nums[k-1] {
k++
continue
}
if m < l-1 && nums[m+1] == nums[m] {
m--
continue
}
if sum > target {
m--
} else if sum < target {
k++
} else {
solutions = append(solutions, []int{nums[i], nums[j], nums[k], nums[m]})
k++
m--
}
}
}
}
return solutions
}
// func main() {
// nums := []int{1, -2, -5, -4, -3, 3, 3, 5}
// //[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
// sort.Ints(nums)
// fmt.Println(nums)
// fmt.Println(len(nums))
// result := fourSum(nums, -11)
// for _, v := range result {
// fmt.Println(v)
// }
// }