189. Rotate Array

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.

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

首先这道题到底是什么意思?
从字面看,是通过K步来旋转N个元素的数组。。。
但其实呢,是将一个数组跳过K个数到右边,也就是将K个数移到开头

  • 思路1
    在LEETCODE上不能通过 - -!
class Solution {
public:
    vector<int> rotate(vector<int>& nums ,int k) {

    if(k>nums.size())
        k %= nums.size();
    vector<int> v;
    for(int i=nums.size()-k; i<nums.size(); i++)
        v.push_back(nums[i]);
    for(int i=0; i<nums.size()-k; i++)
        v.push_back(nums[i]);

    return v;
}
};
  • 思路2

很清晰

class Solution {
public:
    vector<int> rotate(vector<int>& nums ,int k) {

    if(k>nums.size())
        k %= nums.size();

    reverse(nums.begin(),nums.end());
    reverse(nums.begin(),nums.begin()+k);
    reverse(nums.begin()+k,nums.end());

    return nums;
}
};

你可能感兴趣的:(LeetCode)