Skip to content

016. 3Sum Closest (最接近的三数之和)(java) #76

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 1, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Merge pull request #75 from KongJHong/master
Add Solution 066&&073 CPP
  • Loading branch information
yanglbme authored and bluesword12350 committed Nov 1, 2018
commit 4abade037f54c9fb95ef3350e53e91a95024c6c0
17 changes: 17 additions & 0 deletions solution/016. 3Sum Closest/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution {
public int threeSumClosest(int[] nums, int target) {
int result = nums[0]+nums[1]+nums[2];
Arrays.sort(nums);
for(int i = 0;i<nums.length-2;i++){
int start = i+1,end=nums.length-1;
while(start<end){
int cache = nums[i]+nums[start]+nums[end];
if(Math.abs(cache-target)<Math.abs(result-target)) result = cache;
if(cache < target ) start++;
else if(cache > target) end--;
else return result;
}
}
return result;
}
}
You are viewing a condensed version of this merge commit. You can view the full changes here.