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).
双指针法
/** * 双指针法 */ var threeSumClosest = function(nums, target) { // #1 数组排序 nums = nums.sort((a, b) => a - b); // #2 取第一个数 let ans = nums[0] + nums[1] + nums[2]; for (let i = 0; i < nums.length ; i++) { // #3 设定两个指针 let start = i + 1, end = nums.length - 1; while (start < end) { // #4 求和 let sum = nums[start] + nums[end] + nums[i]; // #5 比较绝对值大小 if (Math.abs(sum - target) < Math.abs(ans - target)) ans = sum; // #6 如果相等,直接返回 if (sum === target) return ans; // #7 根据sum大小来缩进两边指针 sum > target ? end-- : start++; } } return ans; };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目描述
算法
答案
The text was updated successfully, but these errors were encountered: