Skip to content

Commit 229181c

Browse files
authored
Merge pull request doocs#76 from bluesword12350/master
016. 3Sum Closest (最接近的三数之和)(java)
2 parents d5af3d2 + 939bb18 commit 229181c

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int threeSumClosest(int[] nums, int target) {
3+
int result = nums[0]+nums[1]+nums[2];
4+
Arrays.sort(nums);
5+
for(int i = 0;i<nums.length-2;i++){
6+
int start = i+1,end=nums.length-1;
7+
while(start<end){
8+
int cache = nums[i]+nums[start]+nums[end];
9+
if(Math.abs(cache-target)<Math.abs(result-target)) result = cache;
10+
if(cache < target ) start++;
11+
else if(cache > target) end--;
12+
else return result;
13+
}
14+
}
15+
return result;
16+
}
17+
}

0 commit comments

Comments
 (0)