533. Two Sum Closest

Leave a comment

July 10, 2016 by oneOokay

Two pointers + Sort

public int twoSumCloset(int[] nums, int target) {
// Write your code here
if (nums == null || nums.length ==0) {
return 0;
}

Arrays.sort(nums);
int i = 0;
int j = nums.length – 1;
int diff = Integer.MAX_VALUE;
while (i < j) {
if(nums[i] + nums[j] > target) {
if(nums[i] + nums[j] – target < diff) {
diff = nums[i] + nums[j] – target;
}
j –;
}else {
if (target – nums[i] – nums[j] < diff) {
diff = target – nums[i] – nums[j];
}
i ++;
}
}
return diff;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: