-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy path3SumClosest.java
55 lines (52 loc) · 1.58 KB
/
3SumClosest.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Solution {
public static int closest;
public static int threeSum;
public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
closest = Integer.MAX_VALUE;
threeSum = Integer.MIN_VALUE;
if (num.length < 3) return 0;
Arrays.sort(num);
for (int i = 0; i < num.length; i++){
calculateTuples(num, target, i);
if (threeSum == target) return threeSum;
while (i + 1 < num.length && num[i + 1] == num[i]){
i++;
}
}
return threeSum;
}
public void calculateTuples(int[] num, int target, int i){
int lp = i + 1;
int rp = num.length - 1;
while(lp < rp){
int sum = num[i] + num[lp] + num[rp];
update3Sum(i, lp, rp, target, num);
if (sum == target){
while (lp + 1 < rp && num[lp + 1] == num[lp]) {
lp ++;
}
lp ++;
while (rp - 1 > lp && num[rp - 1] == num[rp]) {
rp --;
}
rp --;
}
else if (sum < target){
lp ++;
}
else{
rp --;
}
}
}
public void update3Sum(int i, int lp, int rp, int target, int[] num){
int sum = num[lp] + num[rp] + num[i];
int diff = Math.abs(target - sum);
if (diff < closest){
closest = diff;
threeSum = sum;
}
}
}