forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3SumClosest.java
More file actions
31 lines (31 loc) · 951 Bytes
/
3SumClosest.java
File metadata and controls
31 lines (31 loc) · 951 Bytes
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
//O(N^2), o(N)
public class Solution {
public Integer threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
Arrays.sort(num);
int min = Integer.MAX_VALUE;
int result = 0;
for(int i = 0; i < num.length; ++i){
for(int j = i + 1, k = num.length - 1; j < k;){
int sum = num[i] + num[j] + num[k];
int sub = sum - target;
if(sub > 0)
--k;
else if(sub < 0)
++j;
else{
return sum;
}
sub = Math.abs(sub);
if(min > sub){
min = sub;
result = sum;
}
}
while(i < num.length -1 && num[i] == num[i+1])
++i;
}
return result;
}
}