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

    Description

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

    Follow up:

    • 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?

    Example 1:

    Input: nums = [1,2,3,4,5,6,7], 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: nums = [-1,-100,3,99], 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]
    

    Constraints:

    • 1 <= nums.length <= 2 * 10^4
    • It's guaranteed that nums[i] fits in a 32 bit-signed integer.
    • k >= 0

    Analyse

    将数组nums的后k位翻转到数组起始位置

    Input:  [1,2,3,4,5,6,7], k = 3
    Output: [5,6,7,1,2,3,4]  // 5, 6, 7翻转到数组首部
    

    申请临时空间

    原数组与翻转后的数组下标有对应关系
    i -> (i + k) % nums.length

    public void rotate(int[] nums, int k) {
        int len = nums.length;
        k = k % len;
    
        int[] tmp = new int[len];
    
        for (int i = 0; i < len; ++i) {
            tmp[(i + k) % len] = nums[i];
        }
    
        for (int j = 0; j < len; ++j) {
            nums[j] = tmp[j];
        }
    }
    

    reverse三次

    k = 3
    1 2 3 4 5 6 7   // expected 5 6 7 1 2 3 4
    4 3 2 1 5 6 7   // reverse 1 2 3 4
    4 3 2 1 7 6 5   // reverse 5 6 7
    5 6 7 1 2 3 4   // reverse 全部
    

    另一种三次reverse

    k = 3
    1 2 3 4 5 6 7   // expected 5 6 7 1 2 3 4
    4 3 2 1 5 6 7   // reverse 1 2 3 4
    7 6 5 1 2 3 4   // reverse 全部
    5 6 7 1 2 3 4   // reverse 5 6 7
    
    public void reverse(int[] nums, int low, int high) {
        while (low < high) {
            int tmp = nums[low];
            nums[low] = nums[high];
            nums[high] = tmp;
            ++low;
            --high;
        }
    }
    
    public void rotate(int[] nums, int k) {
        k %= nums.length;
        reverse(nums, 0, nums.length - k - 1);
        reverse(nums, nums.length - k, nums.length-1);
        reverse(nums, 0, nums.length-1);
    }
    
  • 相关阅读:
    263邮箱配置告警发件配置
    交换机日期时间设置
    【Switch】- 配置日志文件输出syslog信息
    网络设备断电注意事项
    H3C交换机保存机制
    Docker学习笔记
    小型网络组网模型讲解
    Linux下管理员强行踢出用户的命令使用方法
    Linux SNMP 监控一些常用OID
    MySQL解决方案
  • 原文地址:https://www.cnblogs.com/arcsinw/p/12975758.html
Copyright © 2011-2022 走看看