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
原题链接:https://leetcode-cn.com/problems/two-sum/
解题思路:
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function (nums, target) { // 使用Map缓存数组value与index的关系 let map = new Map(); // 由于value的值可能重复,因此选用队列存储index nums.forEach((value, index) => { if (map.get(value)) { map.get(value).push(index); } else { map.set(value, [index]); } }); // 将数组排序,之后可以根据两数字和与target的大小关系,判断指针的移动方向 nums.sort((a, b) => a - b); // 定义双指针,分别在数组的头尾 let i = 0; let j = nums.length - 1; // 双指针想中间移动 while (i < j) { // 计算当前指针对应的两数字和 let sum = nums[i] + nums[j]; // 如果sum小于target,表示左指针需要向右移动 if (sum < target) { i++; } else if (sum > target) { // 如果sum大于target,表示左指针需要向左移动 j--; } else { // 如果遇到sum等于target,则从队列中取出index,并返回结果 return [map.get(nums[i]).shift(), map.get(nums[j]).shift()]; } } };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接:https://leetcode-cn.com/problems/two-sum/
解题思路:
The text was updated successfully, but these errors were encountered: