189.Rotate Array

August 16, 2016

189.Rotate Array

  • [ TODO 189 use constant space to finish it] 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.

旋转数组,旋转方法就是不断向右移动元素,末尾移至开头。暂时只成功了通过复制新数组进而将合适的元素填入原数组这一种方法,time complexity,space complexity均为O(n),原理见代码:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        if(k<=0)
            return;
        int size=nums.size(),i=0;
        vector<int>nums2(nums.begin(),nums.end());
        for(i=0;i<size;i++){
            nums[(i+k)%size]=nums2[i];
        }
    }
};

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017