您的位置:首页 > 其它

个人记录-LeetCode 16. 3Sum Closest

2016-10-26 21:52 399 查看
问题:

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).


问题要求:找到数组中3个数字,使得它们的和最接近目标。

同样,可以采用LeetCode 11. Container With Most Water类似的解法。

代码示例:

public class Solution {
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 3) {
throw new IllegalArgumentException();
}

//首先将数组变为从小到大排序
Arrays.sort(nums);

int result = nums[0] + nums[1] + nums[2];
//处理特殊情况
if ((target > 0 && nums[nums.length - 1] < 0)
|| (target < 0 && nums[0] > 0)) {
return result;
}

int length = nums.length;
int firstIndex;
int lastIndex;

int curr;
int diff;
int minDiff = Integer.MAX_VALUE;

//固定一个数,逐渐增加
for (int i = 0; i < length - 2; ++i) {
firstIndex = i + 1;
lastIndex = length - 1;

//另外两个数以“夹逼”的方式移动
while (firstIndex < lastIndex) {
curr = nums[i] + nums[firstIndex] + nums[lastIndex];
diff = target - curr;

if (Math.abs(diff) < minDiff) {
minDiff = Math.abs(diff);
result = curr;
}

if (diff > 0) {
//diff > 0,说明当前的和太小了,增加低位下标
++firstIndex;
} else if (diff < 0){
//diff < 0, 说明当前的和太大了,减小高位下标
--lastIndex;
} else {
return target;
}
}
}

return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: