zoukankan      html  css  js  c++  java
  • [LeetCode] Rotate Array

    This problem, as stated in the problem statement, has a lot of solutions. Since the problem requires us to solve it in O(1) space complexity, I only show some of them in the following.

    The first one, also my favorite one, is to apply reverse to nums for three times. You may run some this code on some examples to see how it works.

     1 class Solution {
     2 public:
     3     void rotate(vector<int>& nums, int k) {
     4         int n = nums.size();
     5         k %= n;
     6         reverse(nums.begin(), nums.begin() + n - k);
     7         reverse(nums.end() - k, nums.end());
     8         reverse(nums.begin(), nums.end());
     9     }
    10 };

    The second one is to use swap, and is translated from the C code in this link.

    1 class Solution {
    2 public:
    3     void rotate(vector<int>& nums, int k) {
    4         int start = 0, n = nums.size();
    5         for (; k %= n; n -= k, start += k)
    6             for (int i = 0; i < k; i++)
    7                 swap(nums[start + i], nums[start + n - k + i]);
    8     }
    9 };

    For a more comprehensive summary of other solutions, you may refer to this link (it has 5 solutions).

  • 相关阅读:
    Docker安装nexus
    docker常用操作备忘
    react-01
    SBT实操指南
    Play中JSON序列化
    SPARK安装一:Windows下VirtualBox安装CentOS
    SPARK安装三:SPARK集群部署
    SPARK安装二:HADOOP集群部署
    SLICK基础
    函数式编程
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4653377.html
Copyright © 2011-2022 走看看