[leetcode] 189. Rotate Array

Easy

Given an array, rotate the array to the right by k steps, where k is non-negative.

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

Note:

  • Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
  • Could you do it in-place with O(1) extra space?

题目大意:将数组中的数字向右循环移动k位,比如数组{1,2,3,4,5,6,7},循环右移k=3位变成{5,6,7,1,2,3,4}

方法:

使用数字交换的方法实现数字右移。先把整个数组反转,然后把数组的前k位和后n-k位分别反转。

要注意如果k的值比数组长度大,那么就只要右移多出的那部分就可以了,也就是移动k%n位。

代码如下:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        k = k % n;
        if (k == 0 || nums.size() <= 1)return;
        for (int i = 0; i < (n-1) / 2 + 1; ++i) {
            swap(nums[i], nums[n - 1 - i]);
        }
        for (int j = 0; j < (k-1) / 2 + 1; ++j) {
            swap(nums[j], nums[k - 1 - j]);
        }
        for (int j = k; j < (n + k - 1) / 2 + 1; ++j) {
            swap(nums[j], nums[n - 1 - j + k]);
        }
        return;
    }
};

数组反转的地方也可以直接用vector的reverse函数,代码如下:

class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        int n = nums.size();
        k = k % n;
        if (k == 0 || nums.size() <= 1)return;
        reverse(nums.begin(),nums.end());
        reverse(nums.begin(),nums.begin()+k);
        reverse(nums.begin()+k,nums.end());
        return;
    }
};
原文地址:https://www.cnblogs.com/cff2121/p/11849587.html