zoukankan      html  css  js  c++  java
  • Rotate Array 解答

    Question

    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].

    Solution 1 Bubble Rotate

    Similar with bubble sort, time complexity O(k * n), space cost O(1)

     1 public class Solution {
     2     public void rotate(int[] nums, int k) {
     3         int length = nums.length;
     4         if (k >= length)
     5             k = k % length;
     6         if (k == 0)
     7             return;
     8         for (int i = 0; i < k; i++) {
     9             for (int j = length - 1; j > 0; j--) {
    10                 int tmp = nums[j];
    11                 nums[j] = nums[j - 1];
    12                 nums[j - 1] = tmp;
    13             }
    14         }
    15     }
    16 }

    Solution 2 Traverse

    Key to this solution is to make a copy of original array. Time complexity O(n), space cost O(n).

    Solution 3 Reversal

    Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:

    1. Divide the array two parts: 1,2,3,4 and 5, 6

    2. Rotate first part: 4,3,2,1,5,6

    3. Rotate second part: 4,3,2,1,6,5

    4. Rotate the whole array: 5,6,1,2,3,4

    Time complexity O(n), space cost O(n)

     1 public class Solution {
     2     public void rotate(int[] nums, int k) {
     3         int length = nums.length;
     4         if (k >= length)
     5             k = k % length;
     6         if (k == 0)
     7             return;
     8         reverse(nums, 0, length - k - 1);
     9         reverse(nums, length - k, length - 1);
    10         reverse(nums, 0, length - 1);
    11     }
    12     private void reverse(int[] nums, int start, int end) {
    13         if (start == end || nums.length == 1)
    14             return;
    15         while (start < end) {
    16             int tmp = nums[start];
    17             nums[start] = nums[end];
    18             nums[end] = tmp;
    19             start++;
    20             end--;
    21         }
    22     }
    23 }
  • 相关阅读:
    day32-python阶段性复习六
    golang 项目中坑
    golang crawler
    router
    golang in ubuntu
    go channel 案例分析
    go channel learning
    bee go + mgo
    URL escape and unescape
    [转]good sample of Go
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4799834.html
Copyright © 2011-2022 走看看