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

leetcode:Rotate Array

时间:2015-07-19 14:45:00      阅读:79      评论: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

分析:题意为 将n个元素的数组向右旋转k步

思路:用vector容器的东西来做很简单

代码如下:(O(1) Space

class Solution {
public:
    void rotate(vector<int>& nums, int k) 
    {
        for(int i=0;i<k;i++)
        {
            nums.insert(nums.begin(), nums.back());
            nums.pop_back();
        }
    }
};

然后换种方法:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n=nums.size();
        vector<int> v(n);
        for(int i=n-k,j=0;i<n-1,j<k-1;i++,j++){
            v[j]=nums[i];
        }
        for(int i=0,j=k;i<n-k-1,j<n-1;i++,j++){
            v[j]=nums[i];
        }
        nums=v;
    }
};

出错:Last executed input:[1,2,3,4,5,6], 11  

因为没有考虑到当k大于n的情况,所以需要改进:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> rot(n);
        for(int i = 0; i < n; i++) {
            if((i + k) < n)  rot[i + k] = nums[i];
            if((i + k) >= n) {
                rot[(i + k)%n] = nums[i];
            }
        }
        nums = rot;
    }
};

 

c语言

看看:

 void rotate(int* nums, int numsSize, int k) {
    int i;
    if(k > numsSize)
    k -= numsSize;
    int* temp = (int*)calloc(sizeof(int), numsSize);
    for(i = 0; i < k; i++)
       temp[i] = nums[numsSize - k + i];
    for(; i < numsSize; i++)
       temp[i] = nums[i - k];

     for(i = 0; i < numsSize; i++)
       nums[i] = temp[i];
 }

 或:

void reverse(int *nums, int start, int end) {
    int tmp;
    while (start < end) {
        tmp=nums[start];
        nums[start]=nums[end];
        nums[end]=tmp;
        ++start;
        --end;
    }
}

void rotate(int* nums, int numsSize, int k) {
    k=k%numsSize;
    if (k==0) return;
    reverse(nums,0,numsSize-k-1);
    reverse(nums,numsSize-k,numsSize-1);
    reverse(nums,0,numsSize-1);
}  

  

 

  

 

leetcode:Rotate Array

标签:

原文地址:http://www.cnblogs.com/carsonzhu/p/4658520.html

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