Time O(n) Space O(n) Easy Understanding Solution


  • 0
    N

    Here's my code:

    public class Solution {
        public void rotate(int[] nums, int k) {
            if(k<0) return;
            int kr = k%nums.length;
            if(kr == 0) return;
    
            int[] temp = new int[kr];//Save the rear part of the array to a new array
            for(int i=0; i<kr; i++){
                temp[i] = nums[nums.length-kr+i];
            }
    
            //Move the front part of the array to right
            for(int j=nums.length-1; j>kr-1; j--){
                nums[j] = nums[j-kr];
            }
            
            //Copy the new array to the front of the array
            for(int n=0; n<kr; n++){
                nums[n] = temp[n];
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.