forked from huailian123/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16_threeSumClosest.java
More file actions
29 lines (28 loc) · 825 Bytes
/
Copy path16_threeSumClosest.java
File metadata and controls
29 lines (28 loc) · 825 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
public class Solution {
public int threeSumClosest(int[] nums, int target) {
if(nums == null) return 0;
int result = 0;
if(nums.length<=3){
for(int num: nums){
result+=num;
}
return result;
}
Arrays.sort(nums);
result = nums[0]+nums[1]+nums[2];
for(int i = 0; i < nums.length-2; i++){
int j = i+1;
int k = nums.length-1;
while(j<k){
int sum = nums[i]+nums[j]+nums[k];
if(sum == target) return target;
if(Math.abs(sum-target)<Math.abs(result-target)){
result= sum;
}
if(sum > target) k--;
else j++;
}
}
return result;
}
}