给定一个整数元素的数组,找到这样的t,循环t移位操作将元素变成一个排序数组.如果没有这种t,返回-1



到目前为止我一直在研究的解决方案:

function solution(elements) {
let numOfShifts;
let shift = shiftedArray(elements);
for(i = 0; i < shift.length; i++){

//Here is where i'm getting stuck... how do i continue through the loop even after the first false is returned 
//until all arrays are checked for equality?
if(areEqual(shift[i])){
numOfShifts = i
}else return -1;
}
return numOfShifts;
};

function shiftedArray(array){
let shiftedArrays = [];
for(let i = array.length -1 ; i >= 1; i--){
// first element is simply a formula to create chunk 1
let firstElement = array.length - (i % array.length);

//the result of first element.
let chunk1 = array.slice(firstElement);

//the remaining numbers
let chunk2 = array.slice(0, firstElement);

//Copy of both chunks now merged and pushed into shifted arrays
shiftedArrays.push([...chunk1, ...chunk2]);
};
return shiftedArrays;
}
function areEqual(shift){
let sortedShift = [...shift].sort((a ,b) => {
return a - b
});


//takes in a single shift and does a deep check to see if the array is equal to sorted version
if(sortedShift.length === shift.length){
return sortedShift.every((element, index) => {
if(element === shift[index]){
return true;
}
return false;
})
}
}
console.log(solution([1,4,2,3]));
console.log(solution([[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]]))

即使从areEqual()函数返回了第一个false,我如何保持for循环运行?

附带说明:我知道这可能需要一些重构。。。比如,我之前和某人一起研究过这个问题,他们提到我如何通过编写像shiftArray(arr){return arr.push(arr.pop())}这样的辅助函数来简单地移位数组,但考虑到返回的只是从数组中取出的值,而不是新移位的数组,我不明白这个实现是如何工作的。

您可能做了太多的工作。

假设你有一个由n个整数组成的数组A,索引为零。

分析从索引0到n mod n的数组(因此0两次(。计算后一个整数小于前一个整数的对数,并将第一个索引存储在发生这种情况的位置。

如果计数是1并且位置是k(因此A[k]<A[k-1](,则-k或n-k的循环移位将把A转换为排序数组。如果计数大于1,则没有解决方案。

例如,[4,5,0,1,2,3]——我们看到k=2是唯一一个值低于其前身的索引,并且-2或4的循环移位形成[0,1,3,4,5],它被排序。

最新更新