C# O(n+k%n) time / O(k%n) space Solution


  • 0
    S
    public void Rotate(int[] nums, int k) {
    	int len = nums.Length;
    	
    	k = k % len;
    	if (k == 0) {
    		return;
    	}
    
    	//first store the new beginning
    	int[] arr = new int[k];
    	int ptr = 0;
    	for (int i = len - k; i < len; i++) {
    		arr[ptr] = nums[i];
    		ptr++;
    	}
    
    	for (int i = len - 1; i >= 0; i--) {
    		if (i - k >= 0) {
    			int newElement = nums[i - k];
    			nums[i] = newElement;
    		} else {
    			// now fill the beginning
    			nums[i] = arr[i];
    		}
    	}
    }

Log in to reply
 

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