Advertisement
sweet1cris

Untitled

Jan 9th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.81 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param nums an integer array
  4.      * @param target an integer
  5.      * @return the difference between the sum and the target
  6.      */
  7.     public int twoSumClosest(int[] nums, int target) {
  8.         if (nums == null || nums.length < 2) {
  9.             return -1;
  10.         }
  11.        
  12.         Arrays.sort(nums);
  13.        
  14.         int left = 0, right = nums.length - 1;
  15.         int diff = Integer.MAX_VALUE;
  16.        
  17.         while (left < right) {
  18.             if (nums[left] + nums[right] < target) {
  19.                 diff = Math.min(diff, target - nums[left] - nums[right]);
  20.                 left++;
  21.             } else {
  22.                 diff = Math.min(diff, nums[left] + nums[right] - target);
  23.                 right--;
  24.             }
  25.         }
  26.        
  27.         return diff;
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement