Algorithm to rotate an array in linear time

后端 未结 22 2139
我寻月下人不归
我寻月下人不归 2020-11-28 05:05

How to rotate an integer array by i times using swap function only in linear time.

22条回答
  •  情书的邮戳
    2020-11-28 06:03

    here is my answer using js hope this helps where k is the number of the rotations you want to preform

     var arrayRoatate=function(array,k){
        for(;k>0;k--) {
         var nextElementValue=undefined;
            for (var i = 0; i < array.length; i=i+2) {
                var nextElement = i + 1;
                if (nextElement >= array.length)
                    nextElement = nextElement - array.length;
                var tmp=array[i];
                if(nextElementValue!==undefined)
                    array[i]=nextElementValue
                nextElementValue=array[nextElement];
                array[nextElement]=tmp;
    
            }
        }
    return array;
    

提交回复
热议问题