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
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。 例如,给定数组 nums = [-1,2,1,-4], 和 target = 1. 与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2). 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/3sum-closest 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
The text was updated successfully, but these errors were encountered:
/** * @param {number[]} nums * @param {number} target * @return {number} */ var threeSumClosest = function(nums, target) { const len = nums.length if (len === 3) return nums.reduce((a, b) => a + b) nums = nums.sort((a, b) => a - b) let sum = nums[0] + nums[1] + nums[2] for (let i = 0; i < len; i++) { let l = i + 1 let r = len - 1 while (l < r) { const current = nums[i] + nums[l] + nums[r] if (Math.abs(current - target) < Math.abs(sum - target)) { sum = current } if (current > target) { r-- } else if (current < target) { l++ } else { return current } } } return sum };
Sorry, something went wrong.
与三数之和类似 #6
No branches or pull requests
The text was updated successfully, but these errors were encountered: