forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3Sum Closest.java
More file actions
27 lines (23 loc) · 742 Bytes
/
3Sum Closest.java
File metadata and controls
27 lines (23 loc) · 742 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
class Solution {
public int threeSumClosest(int[] nums, int target) {
int sum = Integer.MAX_VALUE;
Arrays.sort(nums);
for (int i=0; i<nums.length; i++) {
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int tempSum = nums[i] + nums[j] + nums[k];
if (sum == Integer.MAX_VALUE || Math.abs(sum - target) > Math.abs(target - tempSum)) {
sum = tempSum;
}
if (tempSum > target) {
k--;
}
else {
j++;
}
}
}
return sum;
}
}