forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclosest3sum.java
More file actions
executable file
·35 lines (32 loc) · 1018 Bytes
/
closest3sum.java
File metadata and controls
executable file
·35 lines (32 loc) · 1018 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
32
33
34
35
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<Integer> numArr = new ArrayList<Integer>();
for(int i=0;i<num.length;i++){
numArr.add(num[i]);
}
int difference = Integer.MAX_VALUE;
Collections.sort(numArr);
for(int i=0;i<numArr.size()-2;i++){
int j=i+1;
int k=numArr.size()-1;
while(j<k){
int tmp = numArr.get(i)+numArr.get(j)+numArr.get(k) - target;
if(tmp<0){
j++;
}else if(tmp>0){
k--;
}else{
return target;
}
if(Math.abs(tmp)<Math.abs(difference)){
difference = tmp;
}
}
}
return difference+target;
}
}