File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
solution/0016.3Sum Closest Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ func threeSumClosest (nums []int , target int ) int {
2
+ sort (nums )
3
+ lenNums := len (nums )
4
+ result := nums [0 ] + nums [1 ] + nums [2 ]
5
+ for i , n := range nums {
6
+ left := i + 1
7
+ right := lenNums - 1
8
+ for left < right {
9
+ r := nums [left ] + nums [right ] + n
10
+ if abs (r - target ) < abs (result - target ) {
11
+ result = r
12
+ }
13
+ if r > target {
14
+ right --
15
+ } else if r < target {
16
+ left ++
17
+ } else {
18
+ return result
19
+ }
20
+ }
21
+ }
22
+ return result
23
+ }
24
+
25
+ func abs (a int ) int {
26
+ if a >= 0 {
27
+ return a
28
+ }
29
+ return - a ;
30
+ }
31
+
32
+ // quick sort
33
+ func sort (array []int ) {
34
+ if len (array ) == 0 {
35
+ return
36
+ }
37
+ left := 0
38
+ right := len (array ) - 1
39
+ obj := array [left ]
40
+ for left < right {
41
+ for left < right && array [right ] >= obj {
42
+ right --
43
+ }
44
+ array [left ] = array [right ]
45
+
46
+ for left < right && array [left ] <= obj {
47
+ left ++
48
+ }
49
+ array [right ] = array [left ]
50
+ }
51
+ array [left ] = obj
52
+ sort (array [:left ])
53
+ sort (array [right + 1 :])
54
+ }
You can’t perform that action at this time.
0 commit comments