刷题目录
【leetcode】1、两数之和
【leetcode】2、两数相加
【leetcode】7、整数反转
【leetcode】9、回文数
【leetcode】11、盛最多水的容器
【leetcode】14、最长公共前缀
【leetcode】16、最接近的三数之和
描述
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
Related Topics
- 数组
- 双指针
题解
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int ans = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length; i++) {
int start = i + 1;
int end = nums.length - 1;
while (start < end) {
int sum = nums[i] + nums[start] + nums[end];
if (Math.abs(target - sum) < Math.abs(target - ans)) {
ans = sum;
}
if (sum > target) {
end--;
} else if (sum < target) {
start++;
} else {
return ans;
}
}
}
return ans;
}
欢迎大家一起讨论交流学习,leetcode 每日一更
我的 github 期待你的关注
本文详细解析LeetCode上的经典题目——最接近的三数之和,提供了一种高效的解决方案,利用数组排序和双指针技巧,以O(n^2)的时间复杂度找到与目标值最接近的三个数的和。通过实例演示了算法的具体实现过程。
4671

被折叠的 条评论
为什么被折叠?



