Rotate Array

 1  class Solution {
 2 public:
 3     void rotate(vector<int>& nums, int k) {
 4         int n=nums.size();
 5         k%=n;
 6         if(k==0)
 7             return;
 8         reverse(nums,0,n-k-1);
 9         reverse(nums,n-k,n-1);
10         reverse(nums,0,n-1);
11     }
12     void reverse(vector<int>& nums,int s,int e)
13     {
14         while(s<e)
15         {
16             int tmp=nums[s];
17             nums[s]=nums[e];
18             nums[e]=tmp;
19             s++;
20             e--;
21         }
22     }
23 };
View Code

将[n-k,n),[0,n-k),[0,n)翻转即是答案

posted @ 2015-06-10 15:32  varcom  阅读(147)  评论(0编辑  收藏  举报