Rotate Array【189】

Datetime:2016-08-23 01:22:25          Topic: LeetCode           Share

189. Rotate Array

My Submissions

Total Accepted:  55073 Total Submissions:  278176 Difficulty:  Easy

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.

[show hint]

Hint:

Could you do it in-place with O(1) extra space?

Related problem: Reverse Words in a String II

Credits:

Special thanks to  @Freezen for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

Hide Tags
Array

第一种方法:申请额外vector来处理

//思路首先:题目要求用三种方法
//第一种:申请额外空间O(N),用vector直接处理(k会越界,尼玛)
//找规律:原数组中i位置的数据就是tmpnums中(i+k+len)/ len的数据
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
    k=k%nums.size();    
    vector<int> tmpnums(nums.size());
    for (int i=0;i<nums.size();i++)
        tmpnums[(i+k+nums.size())%nums.size()]=nums[i];
    nums=tmpnums;
    }
};




About List