leetcode 189: Rotate Array

来源:互联网 发布:迅雷 知乎 编辑:程序博客网 时间:2024/05/06 15:25

Use queue to save the numbers need to be rotated. The problem means to rotate to the right direction, but I do it to the left direction, so I change k to n-(k%n).

class Solution {public:    void rotate(vector<int>& nums, int k) {        int n=nums.size();        k=n-(k%n);        queue<int> q;        int i,j;        for(i=0;i<k;i++)            q.push(nums[i]);        for(j=0;i<n;i++,j++)            nums[j]=nums[i];        while(!q.empty())        {            nums[j++]=q.front();            q.pop();        }    }};


0 0
原创粉丝点击