gpt4 book ai didi

javascript - Codility CyclicRotation Javascript 解决方案 : Empty array returns an error

转载 作者:行者123 更新时间:2023-11-30 08:20:27 24 4
gpt4 key购买 nike

我正在尝试解决 this problem在适应性中。我的解决方案通过了所有测试,除了一个以空数组和 1 的旋转作为参数的测试。我不知道如何解决这个问题。有人可以把我推向正确的方向吗?除了为空数组检查编写特定的 if 子句。我想不出更优雅的解决方案。

function solution(A, K)
{
for (i=0; i<K; i++)
{
A.unshift(A.pop());
}
return A;
}

最佳答案

一种解决方案是在循环 conditions 部分检查 A.length

function solution(A, K)
{
for (i = 0; i < K && A.length; i++)
{
A.unshift(A.pop());
}
return A;
}

console.log(solution([3, 8, 9, 7, 6], 3));
console.log(solution([], 5));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

但是,您可以使用另一种方法使用 Array.slice() :

function solution(A, K)
{
let i = A.length - (K % (A.length || 1));
return [...A.slice(i), ...A.slice(0, i)];
}

console.log(solution([3, 8, 9, 7, 6], 3));
console.log(solution([], 0));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

关于javascript - Codility CyclicRotation Javascript 解决方案 : Empty array returns an error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54394480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com