一个笔试题

2019-04-03  本文已影响0人  Simon_King

需求

有一个数组,输出任意两个相加等于指定值的数字

实现思路

从第index个开始,跟index+1相加是否等于total, 是就打印出来
每一轮都从index+1开始对比,以免重复

     // 输出两个相加等于total的数
    const total = 6;
    const arr = [1,2,2,4,5,4,3,2,3,4,6,3];
    const len = arr.length;
    arr.forEach((item,index, array) => {        
        for (let j = index + 1; j < len - index; j++) {
            if ((item + array[j]) === total) {
                console.log([item, array[j]]);
                console.log(`下标是${index}, ${j}`);
            }
        }
    });
上一篇 下一篇

猜你喜欢

热点阅读