Skip to content

求两数之和 #259

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

Open
wuxianqiang opened this issue Mar 29, 2020 · 0 comments
Open

求两数之和 #259

wuxianqiang opened this issue Mar 29, 2020 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

问题描述:给定一个数组,数组里面有两个数,他们的和是target,求这两个数在数组中的位置

思路:

  1. a + b = target
  2. 已知 target
  3. 求 a 和 b
function solution(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    let a = nums[i]
    for (let j = i + 1; j < nums.length; j++) {
      let b = nums[j]
      if (b === target - a) {
        console.log(i, j)
      }
    }
  }
}
solution([1, 2, 3, 4], 5)

分析:

  1. 传入[1, 2, 3, 4]
  2. 1和2、3、4对比是否等于target
  3. 2和3、4对比是否等于target
  4. 3和4对比是否等于target

注意:自己不要和自己对比,就是a不能和b相等,因为他是不同的两个数字。

两数之和三数之和都可以这么算

function solution(list, target) {
  let result = []
  for (let i = 0; i < list.length; i++) {
    for (let j = i + 1; j < list.length; j++) {
      let a = list[i];
      let b = list[j];
      if (a + b === target) {
        result.push([a, b])
      }
    }
  }
  return result
}

function solution(list, target) {
  let result = []
  for (let i = 0; i < list.length; i++) {
    for (let j = i + 1; j < list.length; j++) {
      for (let k = j + 1; k < list.length; k++) {
        let a = list[i]
        let b = list[j]
        let c = list[k]
        if (a + b + c === target) {
          result.push([a, b, c])
        }
      }
    }
  }
  return result
}
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