@@ -25,13 +25,75 @@ The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
25
25
### ** Python3**
26
26
27
27
``` python
28
-
28
+ class Solution :
29
+ def threeSumClosest (self , nums : List[int ], target : int ) -> int :
30
+ def twoSumClosest (nums , start , end , target ):
31
+ res = 0
32
+ diff = 10000
33
+ while start < end:
34
+ val = nums[start] + nums[end]
35
+ if val == target:
36
+ return val
37
+ if abs (val - target) < diff:
38
+ res = val
39
+ diff = abs (val - target)
40
+ if val < target:
41
+ start += 1
42
+ else :
43
+ end -= 1
44
+ return res
45
+
46
+ nums.sort()
47
+ res, n = 0 , len (nums)
48
+ diff = 10000
49
+ for i in range (n - 2 ):
50
+ t = twoSumClosest(nums, i + 1 , n - 1 , target - nums[i])
51
+ if abs (nums[i] + t - target) < diff:
52
+ res = nums[i] + t
53
+ diff = abs (nums[i] + t - target)
54
+ return res
29
55
```
30
56
31
57
### ** Java**
32
58
33
59
``` java
34
-
60
+ class Solution {
61
+ public int threeSumClosest (int [] nums , int target ) {
62
+ Arrays . sort(nums);
63
+ int res = 0 ;
64
+ int n = nums. length;
65
+ int diff = Integer . MAX_VALUE ;
66
+ for (int i = 0 ; i < n - 2 ; ++ i) {
67
+ int t = twoSumClosest(nums, i + 1 , n - 1 , target - nums[i]);
68
+ if (Math . abs(nums[i] + t - target) < diff) {
69
+ res = nums[i] + t;
70
+ diff = Math . abs(nums[i] + t - target);
71
+ }
72
+ }
73
+ return res;
74
+ }
75
+
76
+ private int twoSumClosest (int [] nums , int start , int end , int target ) {
77
+ int res = 0 ;
78
+ int diff = Integer . MAX_VALUE ;
79
+ while (start < end) {
80
+ int val = nums[start] + nums[end];
81
+ if (val == target) {
82
+ return val;
83
+ }
84
+ if (Math . abs(val - target) < diff) {
85
+ res = val;
86
+ diff = Math . abs(val - target);
87
+ }
88
+ if (val < target) {
89
+ ++ start;
90
+ } else {
91
+ -- end;
92
+ }
93
+ }
94
+ return res;
95
+ }
96
+ }
35
97
```
36
98
37
99
### ** ...**
0 commit comments