Skip to content
New issue

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

2018/09/04 关于twoSum问题 #32

Open
ChenPt opened this issue Sep 4, 2018 · 0 comments
Open

2018/09/04 关于twoSum问题 #32

ChenPt opened this issue Sep 4, 2018 · 0 comments
Labels
笔试题 校招遇到做错的笔试题或者有趣的笔试题

Comments

@ChenPt
Copy link
Owner

ChenPt commented Sep 4, 2018

给出一个无序的的数组和一个target,找出数组内两个元素的和为target,输出这两个元素的序号。
example

输入: 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
  }
}

因为是无序数组,所以不能将其进行排序,否则输出的序号值有误。

@ChenPt ChenPt added the 笔试题 校招遇到做错的笔试题或者有趣的笔试题 label Sep 4, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
笔试题 校招遇到做错的笔试题或者有趣的笔试题
Projects
None yet
Development

No branches or pull requests

1 participant