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

[leetcode 189] Rotate Array

时间:2015-07-22 09:23:15      阅读:119      评论: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.

[show hint]

Related problem: Reverse Words in a String II

 

[Solution]

先把A[k, n-1] 存储到临时空间, 移动A[0, k-1]。O(k)辅助存储

void rotate(vector<int>& nums, int k) 
    {
        int n = nums.size();
        if (n == 0 || k <= 0)
            return;
            
        k = k % n;
        vector<int> buf(k, 0);
        for (int i = 0; i < k; i++)
            buf[i] = nums[n - k + i];
        
        for (int i = n - 1; i >= k; i--)
            nums[i] = nums[i - k];
        
        for (int i = 0; i < k; i++)
            nums[i] = buf[i];

    }
原地交换:
数组由AB两部分组成,移动k个位置形成BA
用r(A)表示A的逆序,则有r(r(A)) = A
r(AB)= r(B)r(A)
再将r(B), r(A)分别取逆得到BA
 1 void rotate(vector<int>& nums, int k) 
 2     {
 3         int n = nums.size();
 4         if (n == 0 || k <= 0)
 5             return;
 6             
 7         k = k % n;
 8         reverse(nums, 0, n - 1);
 9         reverse(nums, 0, k - 1);
10         reverse(nums, k, n - 1);
11     }
12     
13     void reverse(vector<int>& nums, int s, int e)
14     {
15         for (int i = s, j = e; i < j; i++, j--)
16             swap(nums[i], nums[j]);
17     }

 

[leetcode 189] Rotate Array

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4666278.html

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