Skip to content

Instantly share code, notes, and snippets.

@Roger7410
Created October 12, 2016 04:59
Show Gist options
  • Select an option

  • Save Roger7410/f5bd25f3f14356139535624e9c205254 to your computer and use it in GitHub Desktop.

Select an option

Save Roger7410/f5bd25f3f14356139535624e9c205254 to your computer and use it in GitHub Desktop.
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