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