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
给出一个无序的的数组和一个target,找出数组内两个元素的和为target,输出这两个元素的序号。 example
target
输入: nums = [2,3,7,9], target = 9 输出:[0, 2] 输入:nums = [2,3,7,9] target = 5 输出:[0, 1]
思路: 可以使用两个for循环来遍历数组的每两个元素的组合 思路二: 利用一个对象或者map结构。 遍历数组,将target值减去数组每一项,将差值作为key,当前数组元素的序号作为值存到一个键值对数据结构中(map / object)。每一次遍历数组元素,都去验证当前数组元素与target的差值是否存在于map中,存在的话,value值是否与当前数组元素的序号相同,如果不相同,则说明找到了两个元素的和为target。序号分别是map[nums[i]] 和 i
代码如下
var twoSum = function(nums, target) { let map = {} for(let i = 0; i < nums.length; i++) { let diff = target - nums[i] // 求出差值 if(map[nums[i]] !== undefined && map[nums[i]] !== i) { return [map[nums[i]], i] } map[diff] = i } }
因为是无序数组,所以不能将其进行排序,否则输出的序号值有误。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
给出一个无序的的数组和一个target,找出数组内两个元素的和为
target
,输出这两个元素的序号。example
思路: 可以使用两个for循环来遍历数组的每两个元素的组合
思路二: 利用一个对象或者map结构。
遍历数组,将target值减去数组每一项,将差值作为key,当前数组元素的序号作为值存到一个键值对数据结构中(map / object)。每一次遍历数组元素,都去验证当前数组元素与target的差值是否存在于map中,存在的话,value值是否与当前数组元素的序号相同,如果不相同,则说明找到了两个元素的和为target。序号分别是map[nums[i]] 和 i
代码如下
因为是无序数组,所以不能将其进行排序,否则输出的序号值有误。
The text was updated successfully, but these errors were encountered: