LeetCode 16 最接近的三数之和
Posted Starzkg
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 16 最接近的三数之和相关的知识,希望对你有一定的参考价值。
https://leetcode-cn.com/problems/3sum-closest/
解决方案
class Solution
public int threeSumClosest(int[] nums, int target)
int n = nums.length;
Arrays.sort(nums);
int abs = Integer.MAX_VALUE;
int ans = 0;
for (int i = 0; i < n - 2; i++)
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < n - 1; j++)
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int target0 = -nums[i] - nums[j] + target;
int l = j + 1, r = n - 1;
while (l <= r)
int mid = (l + r) >> 1;
int sub = target0 - nums[mid];
if (Math.abs(sub) < abs)
ans = nums[i] + nums[j] + nums[mid];
abs = Math.abs(sub);
if (sub < 0)
r = mid - 1;
else if (sub > 0)
l = mid + 1;
else
return target;
return ans;
以上是关于LeetCode 16 最接近的三数之和的主要内容,如果未能解决你的问题,请参考以下文章