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

[leetcode] Rotate Array

时间:2015-03-04 18:19:03      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
 
空间复杂度为O(1)。
 
 1 class Solution
 2 {
 3 public:
 4   void rotate(int nums[], int n, int k)
 5   {
 6     if(k == 0 || k == n)
 7       return;
 8 
 9     if(k > n)
10       k = k - n;
11 
12     int m = 0;
13     for(int i=0; i<k; i++)
14     {
15       m = nums[n-i-1];
16       for(int j=n-i-1; j>=0;)
17       {
18         if(j-k >= 0)
19           nums[j] = nums[j-k];
20         else
21           nums[j] = m;
22 
23         j -= k;
24       }
25     }
26 
27     int len = n % k;
28     if(len != 0)
29       rotate(nums, k, k - len);
30   }
31 };

 

[leetcode] Rotate Array

标签:

原文地址:http://www.cnblogs.com/lxd2502/p/4313745.html

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