189. Rotate Array

来源:互联网 发布:sql日月年转年月日 编辑:程序博客网 时间:2024/06/05 21:18

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可能大于n

Approach #1

class Solution {public:    void rotate(vector<int>& nums, int k) {        int n=nums.size();        vector<int> tmp(nums);//void        int j=0;        for(int i=0;i<n;i++)        {            nums[(i+k)%n]=tmp[i];//移动数据        }    }};

时间复杂度:O(n)

空间复杂度:O(n)


Approach #2

每次把最后一个数据往前复制,其他数据往后挪,重复k次


原创粉丝点击