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.

答案:

数组的循环右移:

      三次翻转,时间复杂度为o(n),不用开辟另外的空间

 1 class Solution {
 2 public:
 3     void rotate(vector<int>& nums, int k) {
 4         int i,temp,n;
 5         n=nums.size();
 6         if(n==0){
 7             return;
 8         }
 9         else{
10         k=k%n;
11         for(i=0;i<(n-k)/2;i++){
12             temp=nums[i];
13             nums[i]=nums[n-k-1-i];
14             nums[n-k-1-i]=temp;
15         }
16         for(i=n-k;i<(n*2-k)/2;i++){
17             temp=nums[i];
18             nums[i]=nums[n*2-k-1-i];
19             nums[n*2-k-1-i]=temp;
20         }
21         for(i=0;i<n/2;i++){
22             temp=nums[i];
23             nums[i]=nums[n-1-i];
24             nums[n-1-i]=temp;
25         }
26       } 
27     }
28 };

注意sizeof()和size()的用法:

size()是某一类中定义的一个求大小(长度)的函数,如string a; a.size()求a的大小。
sizeof()是c语言中定义的一种标准标识符,用于求变量的空间大小,如string a;sizeof(a)求的是a所占内存空间的大小。
posted @ 2016-07-05 16:30  绵绵思远道  阅读(123)  评论(0编辑  收藏  举报