We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difficulty: 中等
Related Topics: 数组, 双指针, 排序
给你一个长度为 n 的整数数组 nums和 一个目标值 target。请你从 nums中选出三个整数,使它们的和与 target 最接近。
n
nums
target
返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
输入:nums = [-1,2,1,-4], target = 1 输出:2 解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
示例 2:
输入:nums = [0,0,0], target = 1 输出:0
提示:
3 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
Language: JavaScript
/** * @param {number[]} nums * @param {number} target * @return {number} */ var threeSumClosest = function(nums, target) { let ans = nums[0] + nums[1] + nums[2] if (nums.length === 3) return ans nums.sort((a, b) => a - b) let len = nums.length for (let i = 0; i < len; i++) { let l = i + 1 let r = len - 1 while (l < r) { let tempNum = nums[i] + nums[l] + nums[r] if (Math.abs(target - tempNum) < Math.abs(target - ans)) { ans = tempNum } if (tempNum > target) { r-- } else if (tempNum < target) { l++ } else { return tempNum } } } return ans };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
16. 最接近的三数之和
Description
Difficulty: 中等
Related Topics: 数组, 双指针, 排序
给你一个长度为
n
的整数数组nums
和 一个目标值target
。请你从nums
中选出三个整数,使它们的和与target
最接近。返回这三个数的和。
假定每组输入只存在恰好一个解。
示例 1:
示例 2:
提示:
3 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: