Created
October 12, 2016 04:59
-
-
Save Roger7410/f5bd25f3f14356139535624e9c205254 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Solution { | |
| public int threeSumClosest(int[] nums, int target) { | |
| //each input would have exactly one solution | |
| int result = 0; | |
| Arrays.sort(nums); | |
| //i j k are indexs | |
| int i = 0; | |
| int minCloset = Integer.MAX_VALUE; | |
| while(i < nums.length - 2){ | |
| int j = i + 1; | |
| int k = nums.length - 1; | |
| while(j < k){ | |
| int sum = nums[i] + nums[j] + nums[k]; | |
| int closet = Math.abs(sum - target); | |
| if(closet < minCloset){ | |
| minCloset = closet; | |
| result = sum; | |
| } | |
| if(sum == target) return sum; | |
| if(sum < target) while(nums[j] == nums[++j] && j < k); | |
| if(sum > target) while(nums[k] == nums[--k] && j < k); | |
| } | |
| if(nums[i] > target) break; | |
| while(nums[i] == nums[++i] && i < nums.length - 2); | |
| } | |
| return result; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment