您的位置:首页 > 其它

数组实例记录

2019-07-03 15:33 337 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_35423431/article/details/94560623

1-3题目作者
给出来的都是自己的解法
1、寻找两个数组中相同的元素中最小的元素

const a = [1, 2, 3,4,5, 9, 10]
const b = [3, 4, 6, 7,8,9, 10]
function calc(a,b){
let c = a.filter((num) => {
return b.indexOf(num) !== -1
})
return c[0]
}
console.log(calc(a,b))
--------------------------------------------------------
作者解法:
function findElement (a, b) {
let i = j = 0
while (i < a.length || j < b.length) {
if (a[i] === b[j]) {
return a[i]
} else if (a[i] > b[j]) {
j ++
} else if (a[i] < b[j]) {
i ++
}
}
return null
}

console.log(findElement(a, b))

2、打印数组全排列
[1,2,3] => [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
看作者解法吧,没想到解法

3、有序二维数组寻找某元素坐标

const data = [[1, 2, 5, 9, 10],
[12, 22, 35, 49, 51],
[61, 62, 75, 79, 81]]
function test(arr, num){
let result = []
arr.map((item, index) => {
// item是数组中的一维数组,index表示是第几个一维数组,
// 通过indexOf查看num是否在该一维数组中,在则index是x坐标。
// indexOf表示在一维数组中的位置
let posi = item.indexOf(num)
if(posi !== -1){
result.push(index)
result.push(posi)
}
})
return result
}

console.log(test(data,9))
//作者用的二分查找法,

4、计算给定数组 arr 中所有元素的总和

const data = [1, 2, 5, 9, 10]
function test(arr){
let result = arr.reduce((prev, cur) => {
// prev是上次计算后的结果,cur是当前值
return prev += cur
})
return result
}
console.log(test(data))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: