前端算法之 找出某个数组中的两个数之和跟目标值相等,并获取这两个数在数组中的位置

 此函数,规避了数组中的某个数值被重复使用的问题,譬如说 传入的数组为[2,2,3,4,5]目标值是4,得到值不会是[0,0]而是[0,1]

var twoSum = function(nums, target) {
    let ayy = [];
    for (let i=0; i<nums.length; i++) {
         let initAry = nums.concat();//测出一定要深度拷贝,不然的话下面做切割会影响到原来的数组
         let firstIndex = i,
             endIndex = "";
             let firstValue = nums[i];
             initAry.splice(i,1);//剔除当前所选中的元素,防止这个元素被重复使用
             endIndex = initAry.findIndex((value, index) => {
                return value == target-firstValue
             });
             if (endIndex != -1) {
                ayy.push(i);
                ayy.push(endIndex +1);
                break;
            }
         }
         return ayy;
        };
        var acc = [1, 3, 5, 8];
        console.log(twoSum(acc, 8))// [1,2]
        

猜你喜欢

转载自blog.csdn.net/weixin_39090097/article/details/85013502
今日推荐