zoukankan      html  css  js  c++  java
  • Leetcode: 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.
    
    [show hint]
    
    Hint:
    Could you do it in-place with O(1) extra space?

    Naive想法就是保存一个原数组的拷贝,然后把原数组分成前len-k个元素和后k个元素两部分,把后k个元素放到前len-k个元素前面去。这样做需要O(N)空间

    in-place做法是: 

    (1) reverse the array;

    (2) reverse the first k elements;

    (3) reverse the last n-k elements.

    The first step moves the first n-k elements to the end, and moves the last k elements to the front. The next two steps put elements in the right order.

     1 public class Solution {
     2     public void rotate(int[] nums, int k) {
     3         int len = nums.length;
     4         k %= len;
     5         reverse(nums, 0, len-1);
     6         reverse(nums, 0, k-1);
     7         reverse(nums, k, len-1);
     8     }
     9     
    10     public void reverse(int[] nums, int l, int r) {
    11         while (l <= r) {
    12             int temp = nums[l];
    13             nums[l] = nums[r];
    14             nums[r] = temp;
    15             l++;
    16             r--;
    17         }
    18     }
    19 }

    需要注意的是第4行,右移偏移量k可能比数组长度len要大,所以要先 k%=len;

  • 相关阅读:
    inputstream和outputstream读写数据模板代码
    如何显示包的上一层包
    我的cnblogs设置代码
    myeclipse ctrl+shift+F失效
    数据包加密解密
    用VisualSVN Server创建版本库,以及TortoiseSVN的使用
    权限验证MVC
    Asp.net MVC23 使用Areas功能的常见错误
    MVC基础知识
    最全的Resharper快捷键汇总
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4306556.html
Copyright © 2011-2022 走看看