Tag Archives: JAVE LeetCode 189

Leetcode solution 189 Rotate Array Java version

189. Rotate Array
Rotate an array of n elements to the right byk steps.
For example, with n = 7 and k = 3, the array[1,2,3,4,5,6,7] is rotated to[5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
[show hint]Hint:
Could you do it in-place with O(1) extra space?
given an array of n lengths, rotate it to the right by k positions.first convert k into the number in [0, n-1]. Flip the entire array, flip the number at the [0, K-1] position, and flip the rest.
note that k is positive

	public void rotate(int[] nums, int k) {
		int len = nums.length;
		// Ensure that k is positive
		k = (len + (k % len)) % len;
		// Flip the entire array.
		rotateCore(nums, 0, len - 1);
		// Flip the array of subscript 0~k-1.
		rotateCore(nums, 0, k - 1);
		// Flip the array of subscript k~len-1.
		rotateCore(nums, k, len - 1);

	}

	/**
	 * @param nums
	 *            Flip the array (the subscript is closed front to back).
	 * @param start
	 * Subscript to the beginning of the flipped array
	 * @param end
	 * End subscript for flipping arrays
	 */
	private void rotateCore(int[] nums, int start, int end) {
		for (int i = start, j = end; i < j; i++, j--) {
			nums[i] = nums[i] ^ nums[j];
			nums[j] = nums[i] ^ nums[j];
			nums[i] = nums[i] ^ nums[j];
		}

	}

 

 

JAVE: LeetCode(189) Rotate Array

Q:
Rotate Array Total Accepted: 19161 Total Submissions: 108570 My Submissions Question Solution
Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Here is the code:

/*
Runtime Error Message:	Line 5: java.lang.ArrayIndexOutOfBoundsException: 1
Last executed input:	[-1], 2 
Note: k might be larger num.length - 1.
225 ms
*/
public class Solution {
    void reverse(int[] nums, int start, int end) {
        while(start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            ++start;
            --end;
        }
    }
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        reverse(nums, 0, nums.length - 1 );
        reverse(nums, 0, k - 1 );
        reverse(nums, k, nums.length - 1 );
    }
}