-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreeSumClosest.java
More file actions
33 lines (31 loc) · 914 Bytes
/
ThreeSumClosest.java
File metadata and controls
33 lines (31 loc) · 914 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
package com.leetcode.twopoint;
import java.util.Arrays;
/**
* @author: yhl
* @DateTime: 2021/3/30 14:28
* @Description:
*/
public class ThreeSumClosest {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closeNum = nums[0] + nums[2] + nums[3];
for (int i = 0; i < nums.length - 2; i++) {
int l = i + 1;
int r = nums.length - 1;
while (l < r) {
int threeSum = nums[i] + nums[l] + nums[r];
if (Math.abs(threeSum - target) < Math.abs(closeNum - target)) {
closeNum = threeSum;
}
if (threeSum > target) {
r--;
} else if (threeSum < target) {
l++;
} else {
return target;
}
}
}
return closeNum;
}
}