leetcode解题报告(20):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.

分析

在一个循环里跟踪k的值即可。每一次循环时删除数组最后元素,并把这个元素插入到数组最前面,直到k为0.

代码如下:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if(k <= 0)return;   //border checking
        while(k != 0){
            int rot = nums[nums.size() - 1];//store the laset element before erasing it
            nums.erase(nums.end() - 1); //erase last element
            nums.insert(nums.begin(),rot);//insert last element into beginning of the vector
            --k;    //update k
        }
    }
};
posted @ 2017-05-08 22:35  larryking  阅读(157)  评论(0编辑  收藏  举报