/**
* Similar with 3sum.
* Difference is target now becomes -(nums[i]-1), a
* and also need a variable diff to save the closest distance
* between triplets and targets.
*/
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int res = 0;
int diff = Integer.MAX_VALUE;
Arrays.sort(nums);
for (int i=0; i<nums.length-2; i++) {
if (i == 0 || (nums[i] != nums[i-1])) {
int low = i+1, high = nums.length-1, sum = -nums[i]+target;
while (low < high) {
// if new difference is smaller than current, update both diff and res
if (Math.abs(sum-nums[low]-nums[high]) < diff) {
res = nums[low]+nums[high]+target-sum;
diff = Math.abs(sum-nums[low]-nums[high]);
}
if (nums[low] + nums[high] == sum) return target;
else if (nums[low] + nums[high] > sum) high--;
else low++;
}
}
}
return res;
}
}
Leetcode 16. 3Sum Closest
最新推荐文章于 2021-08-11 08:50:42 发布