Leetcode-189-Rotate Array

Rotate Array:

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].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

 题目解读:

将包含n个元素的数组向右移动k步,正如上面例子所述,当n=7,k=3时,数组[1,2,3,4,5,6,7] 向右循环成为[5,6,7,1,2,3,4]。

解析:首先考虑k的值,当k大于n时,向右循环移动k步和向右移动 k%n=z(求余)步的效果是相同的,为了降低时间复杂度,所以先求出z,再进行向右循环移动。在循环移动时分三步,如下图所示

  1. 将前n-z个元素首尾倒置。
  2. 将后z个元素首尾倒置。
  3. 再将整个数组的元素首尾倒置。

Leetcode-189-Rotate Array_第1张图片
 

Java 代码:

	public static void rotate(int[] nums, int k) {
		if(k>nums.length) {
			k-=nums.length;
		}
		reverse(nums, 0, nums.length-k-1);
		reverse(nums, nums.length-k, nums.length-1);
		reverse(nums, 0, nums.length-1);
	}
	
	public static void reverse(int[] nums, int start, int end){
		int temp = 0;
		while(start < end) {
			temp = nums[start];
			nums[start] = nums[end];
			nums[end] = temp;
			start++;
			end--;
		}
	}

 C代码:

void reverseArray(int nums[], int start, int end){
    int temp = 0;
    while(start < end) {
        temp = nums[start];
        nums[start] = nums[end];
        nums[end] = temp;
        start++;
        end--;
    }
}

void rotate(int nums[], int n, int k) {
    if(k>n) {
        k-=n;
    }
    reverseArray(nums, 0, n-k-1);
    reverseArray(nums, n-k, n-1);
    reverseArray(nums, 0, n-1);
}

 

你可能感兴趣的:(array)