码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Rotate Array

时间:2015-10-11 06:44:49      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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.

Hint:
Could you do it in-place with O(1) extra space?

Related problem: Reverse Words in a String II


解题思路:

要想满足O(1) space and in O(n) time, 只有一种方法: reversal

Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:

1. Divide the array two parts: 1,2,3,4 and 5, 6

2. Rotate first part: 4,3,2,1,5,6

3. Rotate second part: 4,3,2,1,6,5

4. Rotate the whole array: 5,6,1,2,3,4

或者

(1) reverse the array;

(2) reverse the first k elements;

(3) reverse the last n-k elements.

这个方法与 Leetcode Reverse Words in a String II 达成一致。


Java code:

public class Solution {
    public void rotate(int[] nums, int k) {
       int len = nums.length;
       k %= len;
       reverse(nums, 0, len-1);
       reverse(nums, 0, k-1);
       reverse(nums, k, len-1);
    }
    
    public void reverse(int[] nums, int l, int r){
        while(l < r){
            int temp = nums[l];
            nums[l] = nums[r];
            nums[r] = temp;
            l++;
            r--;
        }
    }
}

Reference:

1. http://www.cnblogs.com/EdwardLiu/p/4306556.html

 

Leetcode Rotate Array

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4868716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!