forked from soulmachine/algorithm-essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum-closest.java
More file actions
29 lines (25 loc) · 792 Bytes
/
Copy path3sum-closest.java
File metadata and controls
29 lines (25 loc) · 792 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
// 3Sum Closest
// 先排序,然后左右夹逼
// Time Complexity: O(n^2), Space Complexity: O(1)
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int result = 0;
int minGap = Integer.MAX_VALUE;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; ++i) {
int j = i + 1;
int k = nums.length - 1;
while(j < k) {
final int sum = nums[i] + nums[j] + nums[k];
final int gap = Math.abs(sum - target);
if (gap < minGap) {
result = sum;
minGap = gap;
}
if (sum < target) ++j;
else --k;
}
}
return result;
}
}