Guest User

Untitled

a guest
Oct 23rd, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. public class A3SumClosest {
  2. /*
  3. The idea is to sort an input array first and then run through all indices of a possible first element of a triple.
  4. For each possible first element we make a standard bi-direction 2Sum sweep of the remaining part of the array.
  5. */
  6. public int threeSumClosest(int[] nums, int target) {
  7. Arrays.sort(nums);
  8. int clo = nums[nums.length-3]+nums[nums.length-2]+nums[nums.length-1];
  9. for(int i=0; i<nums.length-2; i++){
  10. int lo = i+1;
  11. int hi = nums.length-1;
  12. int sum = target-nums[i];
  13. while(lo<hi){
  14. if(nums[lo]+nums[hi]==sum){
  15. return target;
  16. } else if(nums[lo]+nums[hi]<sum){
  17. if(Math.abs(target-nums[i]-nums[lo]-nums[hi])<Math.abs(target-clo)){
  18. clo = nums[i]+nums[lo]+nums[hi];
  19. }
  20. lo++;
  21. } else {
  22. if(Math.abs(target-nums[i]-nums[lo]-nums[hi])<Math.abs(target-clo)){
  23. clo = nums[i]+nums[lo]+nums[hi];
  24. }
  25. hi--;
  26. }
  27. }
  28. }
  29. return clo;
  30. }
  31. }
Add Comment
Please, Sign In to add comment