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
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
两个
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
nums[i] + nums[j] === target
[i, j]
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { const len = nums.length for (let i = 0; i < len - 1; i++) { for (let j = i + 1; j < len; j++) { if (nums[i] + nums[j] === target) { return [i, j] } } } }
O(n^2)
O(1)
target - nums[i]
i
哈希表
nums
nums[i]
target
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { const map = new Map() for (let i = 0; i < nums.length; i++) { map.set(target - nums[i], i) } for (let i = 0; i < nums.length; i++) { const ans = map.get(nums[i]) if (ans && ans !== i) { return [ i, map.get(nums[i]) ] } } }
其实这里还能把循环优化成为一个,代码如下🌰:
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { const map = new Map() for (let i = 0; i < nums.length; i++) { const ans = target - nums[i] if (map.has(ans)) { return [ i, map.get(ans) ] } map.set(nums[i], i) } }
O(n)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
题目描述📄
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
题目剖析🧐
一、 暴力搜索
nums[i] + nums[j] === target
时返回[i, j]
O(n^2)
O(1)
思路二、空间换时间 —— 巧用哈希表
target - nums[i]
和i
的值存放在哈希表
中,target - nums[i]
对应i
nums
数组,找到一个存在于哈希表
中的nums[i]
,即找到两个数字之和等于target
其实这里还能把循环优化成为一个,代码如下🌰:
O(n)
O(n)
The text was updated successfully, but these errors were encountered: