繁体   English   中英

编写一个函数,该函数将返回值总和为 5 的两个数字数组组合。我无法获得所有机会

[英]Write a function that will return the two number array combination with value summed at 5. I can't get all the opportunities

一个职位发布要我写一个问题的答案,如果我解决了这个问题,我就有资格进入下一轮。

编写一个函数,该函数将返回总和为 5 的数组组合。重要提示:仅使用一个“for”循环。 示例:var rand_array = [1,3,5,2,4,6]; var target_sum = 5; 输出 = [1,4], [5], [3,2], [2,3], [4,1];

我试图在网上找到解决方案并偶然发现了这一点:

https://www.geeksforgeeks.org/given-an-array-a-and-a-number-x-check-for-pair-in-a-with-sum-as-x/因为 StackOverflow 希望你做先自己研究。

但是,当尝试将其转换为 JS 时,所发生的一切只是它返回了一种可以工作的情况。 我需要它来返回它工作的每个案例。 然后我做了一些其他的改变,它现在停止工作了。

var ra = [1,3,5,2,4,6];
var target = 5


ra.sort();
lower = 0;
higher = ra.length -1;

var solutions = [];
var result;

while (lower < higher) {
        if (ra[lower] + ra[higher] === target){
            result = [ra[lower], ra[higher]];
            solutions.push(result);
        }
        else if (ra[lower] + ra[higher] > target){
            higher--;
        }
        else {
            lower++; 
        }
    }

    return solutions;
}

console.log(solutions);

有人可以为我写一个例子吗?

您的代码不工作,在所有的时刻,因为它并不总是增量lowerhigher (导致无限循环)。 它还具有比必要更大的复杂性( .sort具有复杂性O(n log n) ),但说明表明低复杂性很重要。 该数组也没有按数字排序。 (要按数字排序,请使用.sort((a, b) => a - b)

如果您想要一个尽可能复杂度最低的解决方案, O(n) ,在迭代时,创建一个对象。 在每次迭代中,检查对象是否具有当前数字总和为 5 的键(例如,在迭代1 ,查看对象上是否存在4属性)。 如果找到,请将其添加到解决方案中。 否则,在对象上设置一个新键:

 const ra = [1, 3, 5, 2, 4, 6]; const target = 5; const solutions = []; const obj = {}; for (const item of ra) { const match = target - item; if (obj[match]) { solutions.push([item, match]); delete obj[match]; } else { obj[item] = true; } } console.log(solutions);

如果可能有重复的数字,则在对象中存储一个计数,而不仅仅是true

 const ra = [1, 1, 1, 3, 5, 2, 4, 6, 4, 4]; const target = 5; const solutions = []; const obj = {}; for (const item of ra) { const match = target - item; if (obj[match]) { solutions.push([item, match]); obj[match]--; } else { obj[item] = (obj[item] || 0) + 1; } } console.log(solutions);

我不想写实际的答案,因为它是一项工作分配,但我会说一个简单的 2 循环函数是 obvies 解决方案,而不是尝试认为不从顶部和底部检查数组,就像编队一样循环中的循环。

暗示 :

let i = 0;
let j = 0;

while (i < arr.langth) {
    ...
    if (j < arr.langth) {
        j++;
    } else {
        j = 0;
        i++;
    }
}

您的代码根本不起作用。 某些性能有一个可靠的答案,除了它没有按要求执行任务,即将不同顺序的相同数字视为不同或获取等于目标的值作为解决方案。 这是我对您的问题的解决方案:

 const ra = [1,3,5,2,4,6]; const target = 5 function getSumsOfTarget(ra, target){ ra.sort(); lower = 0; higher = ra.length -1; const solutions = []; let result; while (lower < ra.length && higher >= 0) { const sum = ra[lower] + ra[higher]; if (ra[lower] === target) { result = [ra[lower]]; solutions.push(result); break; } if (sum === target){ result = [ra[lower], ra[higher]]; solutions.push(result); lower++; } else if (sum > target){ higher--; } else { lower++; } } return solutions; } console.log(getSumsOfTarget(ra, target));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM