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

[show hint]

Related problem: Reverse Words in a String II

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

Hide Tags
  Array
 

链接:  http://leetcode.com/problems/rotate-array/

题解:

数组移动问题。可以参考<编程珠玑>里利用三次reverse达成数组向左移动的方法。向右移动k step相当于向左移动数组长度nums.length - k。 要注意提前取摸,使k成为一个合理的值。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public void rotate(int[] nums, int k) {

        k %= nums.length;

        k = nums.length - k;

        reverse(nums, 0, k - 1);

        reverse(nums, k, nums.length - 1);

        reverse(nums, 0, nums.length - 1);

    }

    

    private void swap(int[] nums, int l, int r){

        int temp = nums[l];

        nums[l] = nums[r];

        nums[r] = temp;

    }

    

    private void reverse(int[] nums, int l, int r){

        while(l <= r)

            swap(nums, l ++, r --);

    }

}

 

测试:

Reference:

你可能感兴趣的:(array)