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

输出数组中所有两个的数相加等于7的两个数 #4

Open
MY729 opened this issue Jul 19, 2019 · 0 comments
Open

输出数组中所有两个的数相加等于7的两个数 #4

MY729 opened this issue Jul 19, 2019 · 0 comments

Comments

@MY729
Copy link
Owner

MY729 commented Jul 19, 2019

题目

输出数组中所有两个的数相加等于7的两个数

要求:以数组的形式返回

例如:

给一个数组如下:

let arr = [8, 4, 2, 5, 1, 3, 6, 9]

输出两个数之和为7的两个数:

[[4, 3], [2, 5], [1, 6]]

解析

遍历数组,利用indexOf方法查找,数组中有没有其他数与当前的数相加等7的值

以上面例子为例,要注意的一个点:

要避免重复查找,比如我们遍历到4时,可以找到目标数3, 但当我们遍历到3时,应当注意从3往后找目标数,而非从数组的起始位置查找

indexOf 方法有两个参数:

  • 第一个参数 要查找的数组
  • 第二个参数 规定从数组的哪个位置开始查找 【可选,默认从头开始】

答案

let targetArr = (arr, target) => {
    let newArr = []
    arr.forEach((item, index) => {
        let num = target - item
        let i = arr.indexOf(num, index)
        if (i > -1) {
            newArr.push([item, arr[i]])
        }
    })
    return newArr
}

let arr = [8, 4, 2, 5, 1, 3, 6, 9]
targetArr(arr, 7) // 调用
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