【LeetCode】189 - 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.[show hint]

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

Related problem: Reverse Words in a String II

Solution 1:reverse[1,2,3,4]=[4,3,2,1], reverse[5,6,7]=[7,6,5], reverse[4,3,2,1,7,6,5]=[5,6,7,1,2,3,4]

 1 #include<algorithm>
 2 class Solution {     
 3 public:
 4     void rotate(vector<int>& nums, int k) {      //runtime:24ms
 5         int n=nums.size();
 6         k %= n;
 7         reverse(nums.begin(),nums.begin()+n-k);
 8         reverse(nums.begin()+n-k,nums.end());
 9         reverse(nums.begin(),nums.end());
10     }
11 };

Solution 2:超时

 1 class Solution {
 2 public:
 3     void rotate(vector<int>& nums, int k) {
 4         int n=nums.size();
 5         k %= n;
 6         while(k--){
 7             int temp=nums[n-1];
 8             for(int i=n-1;i>0;i--){
 9                 nums[i]=nums[i-1];
10             }
11             nums[0]=temp;
12         }
13     }
14 };

Solution 3:

1 void rotate(int nums[], int n, int k) {  
2     k = k % n;  
3     if (k == 0) return;  
4     int *temp = new int[n];  
5     memcpy(temp, nums+(n-k), sizeof(int)*k);  
6     memcpy(temp+k, nums, sizeof(int)*(n-k));  
7     memcpy(nums, temp, sizeof(int)*n);  
8     delete[] temp;  
9 }  

 

posted @ 2015-08-04 22:53  irun  阅读(326)  评论(0编辑  收藏  举报