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
最接近的三数和 [-1, 2, 1, 4] target = 1; output =2; (-1 + 2 + 1 = 2)
function threeSum(nums, target) { nums.sort((a, b)=> a-b); let ans = nums[0] + nums[1] + nums[2]; // let res = [nums[0], nums[1], nums[2]]; for(let i = 0; i < nums.length; i++) { let left = i + 1, right = nums.length - 1; while(left < right) { let sum = nums[i] + nums[left] + nums[right]; // 比较 差值大小, 更新 ans if(Math.abs(target - sum) < Math.abs(target - ans)) { // res = [nums[i], nums[left], nums[right]]; ans = sum; } // 更新双指针 if(sum > target) { right--; } else if(sum < target) { left++ } else { return ans; } } } return ans; } console.log(threeSum([-1, 2, 1, 4], 1));
The text was updated successfully, but these errors were encountered:
No branches or pull requests
leetcode 16
最接近的三数和 [-1, 2, 1, 4] target = 1;
output =2; (-1 + 2 + 1 = 2)
解题思路
The text was updated successfully, but these errors were encountered: