3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
public class Solution { public int threeSumClosest(int[] num, int target) { // Start typing your Java solution below // DO NOT write main() function int res = Integer.MAX_VALUE; Arrays.sort(num); for(int i=0;i<num.length;i++){ for(int j=i+1;j<num.length;j++){ int temp = target-(num[i]+num[j]); int start=j+1, end=num.length-1, mid=0; while(start<=end){ mid=(start+end)/2; if(num[mid]==temp){ break; }else if(num[mid]>temp){ end=mid-1; }else if(num[mid]<temp){ start=mid+1; } } if(start<=end){ start=mid; end=mid; } //while(start==i || start==j) // start++; while(end==i || end==j) end++; if(start<num.length) res=Math.abs(num[start]-temp)<Math.abs(res-target)||res==Integer.MAX_VALUE?num[start]-temp+target:res; if(end>0 && end<num.length) res=Math.abs(num[end]-temp)<Math.abs(res-target)||res==Integer.MAX_VALUE?num[end]-temp+target:res; } } return res; } }
1 comment:
Simpler solution:
public class Solution {
public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
Arrays.sort (num);
int res = num[0] + num[1] + num[2] - target;
for (int i = 0; i < num.length - 2; i++) {
int j = i + 1, k = num.length - 1;
while (j < k) {
int d = num[i] + num[j] + num[k] - target;
if (d == 0) return target;
if (Math.abs (d) < Math.abs(res)) res = d;
if (d < 0) j++;
else k--;
}
}
return res + target;
}
}
Post a Comment