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

第 86 题:周一算法题之「两数之和」 #56

Open
DreamLee1997 opened this issue Oct 17, 2019 · 0 comments
Open

第 86 题:周一算法题之「两数之和」 #56

DreamLee1997 opened this issue Oct 17, 2019 · 0 comments

Comments

@DreamLee1997
Copy link
Owner

答案:

1、暴力破解法

function twoSum(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    for (let j = 0; j < nums.length; j++) {
      if (i !== j && nums[i] + nums[j] === target) {
        return [i, j]
      }
    }
  }
}

2、一趟哈希表

var twoSum = function(nums, target) {
  const map = {}
  for (let i = 0; i < nums.length; i++) {
    const n = nums[i]
    if (target - n in map) {
      return [map[target - n], i]
    } else {
      map[n] = i
    }
  }
}
  • 在给哈希表添加元素的同时寻找有没有符合目标的答案,如果有就直接返回,没有就继续构造哈希表。
  • 时间复杂度O(n), 空间复杂度O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant