-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathThreeSum.java
More file actions
49 lines (37 loc) · 949 Bytes
/
ThreeSum.java
File metadata and controls
49 lines (37 loc) · 949 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package TwoPointers;
import java.util.ArrayList;
import java.util.Collections;
/**
* Author - archit.s
* Date - 16/10/18
* Time - 11:30 AM
*/
public class ThreeSum {
public int threeSumClosest(ArrayList<Integer> A, int B) {
int minDiff = Integer.MAX_VALUE;
int sum = 0;
Collections.sort(A);
for(int i=0;i<A.size()-2;i++){
int j=i+1;
int k = A.size()-1;
while(j<k){
int temp = A.get(i) + A.get(k) + A.get(j);
int min = Math.abs(temp - B);
if(temp == B){
return B;
}
if(min < minDiff ){
minDiff = min;
sum = temp;
}
if(temp < B){
j++;
}
else {
k--;
}
}
}
return sum;
}
}