[英]Find the minimum cost combination algorithm
给定一个包含至少 5 个项目的数组 N,我想找到 2 个数字(P 和 Q),其中 0 < P < Q < N - 1。
假设我们有以下数组:
const N = [1, 9, 4, 5, 8];
从这里给出最小成本的组合是P = 2
和Q = 3
。
这是我找到的解决方案,如果我能提高它的时间复杂度,我正在寻求你的帮助:
function solution(N) {
// since 0 < P < Q < N - 1
const sliced = N.slice(1, N.length - 1);
const sorted = sliced.sort((a, b) => a - b);
// the minimum should be from the start since we have sorted the array
const P = 0;
const Q = 1;
return getCost(P, Q, sorted);
}
function getCost(P, Q, N) {
return N[P] + N[Q];
}
// output should be 9
console.log(solution([1, 9, 4, 5, 8]))
在最好的情况下,由于排序,它是0(n log(n)) ,但我想知道我们是否可以将其改进为 O(n)。
谢谢你的帮助
你觉得这个解决方案怎么样?
function solution([_, ...n]) { n.pop() n.sort((a, b) => a - b); return n[0] + n[1]; } // output should be 9 console.log(solution([1, 9, 4, 5, 8]))
逻辑与您概述的逻辑相同 - 仅使用 JS 提供的其他方法。
function twoSmallest(arr) {
let [first, second] = [arr[1], arr[2]]
for (let i = 3; i < arr.length - 1; i++) {
const el = arr[i]
if (el < first && el < second) {
[first, second] = [Math.min(first, second), el]
} else if (el < first) {
[first, second] = [second, el]
} else if (el < second) {
second = el
}
}
return first + second
}
这是一个O(n)
时间和O(1)
空间的解决方案。 它还确保在您需要使用索引并且出于某种原因感兴趣的情况下, first
保留具有较小索引的元素。
算法很清楚,IMO,但 JS 代码可能不是最好的实现。 好久没写JS了。
我很确定这是 O(n):
const solution = (arr) => {
// find smallest that's not at either end
let idx = 1;
let P = arr[1];
for(let i = 2; i < arr.length-1; i++) {
if(arr[i] < P) {
idx = i;
P = arr[i];
}
}
// find second smallest that's not at either end
let Q = Infinity;
for(let i = 1; i < arr.length-1; i++) {
if(i == idx) continue;
if(arr[i] < Q) Q = arr[i];
}
return P + Q;
}
这是使用 Python 在列表中找到 k 个最小数字的最快方法。 rest 是微不足道的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.