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

求两数之和 #14

Open
CodeRookie262 opened this issue Jan 4, 2021 · 1 comment
Open

求两数之和 #14

CodeRookie262 opened this issue Jan 4, 2021 · 1 comment
Labels

Comments

@CodeRookie262
Copy link
Owner

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]
@CodeRookie262
Copy link
Owner Author

暴力破解法(循环嵌套)

function twoSum(arr, target) {
  for (var i = 0, len = arr.length; i < len; i++) {
    for (var j = i + 1; j < len; j++) {
      if (arr[i] + arr[j] === target) return [i, j];
    }
  }
}

哈希表标记

function twoSum(arr, target) {
  let memo = {};

  for (var i = 0; i < arr.length; i++) {
    if (memo[target - arr[i]] === undefined) {
      memo[arr[i]] = i;
    }
    if (memo[target - arr[i]] !== undefined && memo[target - arr[i]] !== i)
      return [memo[target - arr[i]], i];
  }
}

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