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

1. 两数之和 #22

Open
pigpigever opened this issue Oct 25, 2019 · 0 comments
Open

1. 两数之和 #22

pigpigever opened this issue Oct 25, 2019 · 0 comments
Labels
哈希表 哈希表类型的算法题

Comments

@pigpigever
Copy link
Owner

题目描述📄

给定一个整数数组 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 的值存放在 哈希表 中,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)
  • 空间复杂度:O(n)
@pigpigever pigpigever added the 哈希表 哈希表类型的算法题 label Oct 25, 2019
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