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

[LeetCode]Rotate Array

时间:2015-03-10 12:07:57      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:数组循环右移n位

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?

这道题是要求将数组中的元素循环右移k位。

如果k<= n,通过观察可以发现,通过三步可以将要求完成:
①将数组前n-k位反转
②将数组后k位反转
③将数组整体反转

但是,如果k>n,则需要多走一步,就是k=k%n。
代码如下:

class Solution {
public:
    void swap(int& a,int& b){
        int temp=a;
        a=b;
        b=temp;
    }
    void reverse(int nums[],int begin,int end){
        for(int i=begin,j=end;i<j;i++,j--){
            swap(nums[i],nums[j]);
        }
    }
    void rotate(int nums[], int n, int k) {
        int step=k%n;
        reverse(nums,0,n-step-1);
        reverse(nums,n-step,n-1);
        reverse(nums,0,n-1);
    }
};

[LeetCode]Rotate Array

标签:数组循环右移n位

原文地址:http://blog.csdn.net/kaitankedemao/article/details/44173463

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