Rotate Array (LeetCode) 189

Question

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

Solution

解法一:普通解法,依次向右平移k步。先将最后k个元素记录下来,再将前n-k个元素向右平移k步,最后将之前记录下来的k个元素填入原来数组的前k个位置。

解法二:先将前n-k个元素反转,再将后k个元素反转,最后将整个数组反转。这里有个小技巧,交换两个元素a,b时,可以用

a ^= b;
b ^= a;
a ^= b;

结果和传统的用temp交换的方法是一样的。

代码如下:

public class Solution {
    public void rotate(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k == 0) {
            return;
        }

        //reverse version
        // int n = nums.length;
        // k %= n;

        // reverse(nums, 0, n - k - 1);
        // reverse(nums, n - k, n - 1);
        // reverse(nums, 0, n - 1);

        //normal version
        int step = k % nums.length;
        int[] tmp = new int[step];
        for(int i = 0; i < step; i++){
            tmp[i] = nums[nums.length - step + i];
        }
        for(int i = nums.length - step - 1; i >= 0; i--){
            nums[i + step] = nums[i];
        }
        for(int i = 0; i < step; i++){
            nums[i] = tmp[i];

        }
    }

    private void reverse (int[] nums, int start, int end) {
        if (start >= end) {
            return;
        }

        while (start < end) {
            // int temp = nums[start];
            // nums[start] = nums[end];
            // nums[end] = temp;
            nums[start] ^= nums[end];
            nums[end] ^= nums[start];
            nums[start] ^= nums[end];
            start++;
            end--;
        }
    }
}

results matching ""

    No results matching ""