zoukankan      html  css  js  c++  java
  • Rotate Array

    Description:

    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

    Code:

    1.解法1:直接映射

    时间复杂度O(N), 空间复杂度O(N)

     1 void rotate(int nums[], int n, int k) {
     2         //算法1:直接映射
     3         int *p = new int[n];
     4         for (int i = 0; i < n; i++)
     5             p[i] = nums[i];
     6             
     7         for (int i = 0; i < n; i++)
     8         {
     9           nums[(i+k)%n] = p[i];
    10         }
    11         delete []p;
    12     }

    2.解法2:每次移动一步,共循环k次,时间复杂度O(KN),空间复杂度O(1)

     void rotate(int nums[], int n, int k) {
          for (int i = 0; i < k%n; ++i)
         {
                 int temp = nums[n-1];
                 for (int j = n-1; j > 0; --j)
               {
                      nums[j] = nums[j-1];
               }
               nums[0] = temp;
         }
        }

    3.解法3,类似于位反序

  • 相关阅读:
    list和set的区别
    tcp与udp协议的区别
    c3p0的数据库连接池
    mysql的连接
    HAVING 的使用 及笛卡尔积
    break-跳出内循环
    求素数(范围自改)
    1-100累加
    1-100累乘
    类实例:飞机大战
  • 原文地址:https://www.cnblogs.com/happygirl-zjj/p/4598794.html
Copyright © 2011-2022 走看看