-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3sum.java
39 lines (36 loc) · 946 Bytes
/
3sum.java
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
36
37
38
39
public class Solution {
public int threeSumClosest(ArrayList<Integer> A, int B) {
Collections.sort(A);
int max=A.get(0)+A.get(1)+A.get(2);
for(int i=0;i<A.size();i++)
{
int target=B-A.get(i);
int k=i+1;
int l=A.size()-1;
int newmax;
while(k<l)
{
int x=A.get(k);
int y=A.get(l);
newmax=x+y+A.get(i);
if(x+y==target)
{
return B;
}
else if(x+y>target)
{
l--;
}
else
{
k++;
}
if(B-max>B-newmax)
{
max=newmax;
}
}
}
return max;
}
}