leetcode-189.-Rotate Array

来源:互联网 发布:tbi文件怎么导入淘宝 编辑:程序博客网 时间:2024/04/30 01:46

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步。例如,[1,2,3,4,5,6,7] 旋转一步变为[7,1,2,3,4,5,6] 。


利用队列,在队列里旋转好之后,再赋值到vector里。

class Solution {public:    void rotate(vector<int>& nums, int k) {        queue<int>q ;        int n = nums.size();        // 在vector里的元素放进队列里        for (int i = 0 ; i < n ; i ++) {            q.push(nums.back()) ;            nums.pop_back();        }        //将队列的元素进行rotate        for (int i = 0 ; i < k ; i ++) {            int t = q.front() ;            q.pop() ;            q.push(t) ;        }        //在将队列里的元素赋值到原vector里        for (int i = 0 ; i <  n ; i ++) {            nums.push_back(q.front()) ;            q.pop() ;        }                for (int i = 0 ;i<n/2;i++)            swap(nums[i],nums[n-i-1]) ;    }};


0 0
原创粉丝点击