LeetCode16. 最接近的三数之和
一、题目描述
☆☆☆二、解法
思路:与15题三数之和类似, 排序+双指针。
class Solution {publicint threeSumClosest(int[] nums, int target) {/*** 方法1: 排序 + 暴力法, 时间复杂度O(n^3)
*//*Arrays.sort(nums);
int diff = Integer.MAX_VALUE;
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
for (int j = i + 1; j < nums.length - 1; j++) {
if (j > i + 1 && nums[j] == nums[j-1]) continue;
for (int k = j + 1; k < nums.length; k++) {
if (k > j + 1 && nums[k] == nums[k-1]) continue;
int tempDiff = nums[i] + nums[j] + nums[k] - target;
diff = Math.abs(diff) < Math.abs(tempDiff) ? diff : tempDiff;
}
}
}
return target + diff;*/
/**
* 方法2:排序 + 对撞指针, 时间复杂度: O(n^2)
*/
Arrays.sort(nums);
int closeNum = nums[0] + nums[1] + nums[2]; // 注意此初始化
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int start = i + 1, end = nums.length - 1;
while (start < end) {
int tempSum = nums[i] + nums[start] + nums[end];
if (tempSum == target) { // 如果和为 target,肯定是最接近的
return target;
}
if (Math.abs(tempSum - target) < Math.abs(closeNum - target)) {
closeNum = tempSum;
}
if (tempSum > target) {
end --;
}else {
start ++;
}
}
}
return closeNum;
}
}
以上是 LeetCode16. 最接近的三数之和 的全部内容, 来源链接: utcz.com/a/73983.html