LeetCode-Array-189. Rotate Array

来源:互联网 发布:支持php的web服务器 编辑:程序博客网 时间:2024/05/01 20:36

问题:https://leetcode.com/problems/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].
思考:创建一个vector,依次push_back。
C++代码:

class Solution {public:    void rotate(vector<int>& nums, int k) {        int l=nums.size();        vector<int>result;        if(l==1) return ;        if(k>l) k%=l;        for(int i=l-k;i<l;i++){            result.push_back(nums[i]);        }        for(int j=0;j<l-k;j++){            result.push_back(nums[j]);        }        nums=result;    }};
0 0
原创粉丝点击