美文网首页
LeetCode:189. 轮转数组

LeetCode:189. 轮转数组

作者: alex很累 | 来源:发表于2022-02-06 19:30 被阅读0次

问题链接

189. 轮转数组

问题描述

给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k是非负数。

示例

输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]

解题思路

  1. 解法1: 创建一个额外的数组,放置轮转之后的数。
  2. 解法2:运用数组反转的方法,例:
    [1,2,3,4,5,6,7]. 向右轮转2个位置
    A. 整个数组进行翻转,变为: [7,6,5,4,3,2,1]
    B. 左边部分(第0位到第k-1位)进行翻转:[7,6]. =>. [6,7]
    C.右边部分(第k位到最后一位)进行翻转:[5,4,3,2,1] => [1,2,3,4,5]
    D.结果为:[6,7,1,2,3,4,5]

代码示例(JAVA)

创建额外的数组

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

        // for (int i = 0; i < nums.length; i++) {
        //     nums[i] = result[i];
        // }
        System.arraycopy(result, 0, nums, 0, nums.length);
    }
}

数组翻转

class Solution {
    public void rotate(int[] nums, int k) {
        if (k % nums.length == 0) {
            return;
        }
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k % nums.length - 1);
        reverse(nums, k % nums.length, nums.length - 1);
    }

    public void reverse(int[] nums, int start, int end) {
        while (start < end) {
            int temp = nums[start];
            nums[start++] = nums[end];
            nums[end--] = temp;
        }
    }
}

相关文章

  • 63.轮转数组

    day:14 189. 轮转数组[https://leetcode-cn.com/problems/rotate...

  • LeetCode:189. 轮转数组

    问题链接 189. 轮转数组[https://leetcode-cn.com/problems/rotate-ar...

  • 189. 轮转数组

    题目地址(189. 轮转数组) https://leetcode.cn/problems/rotate-array...

  • LeetCode 189. 轮转数组

    题目 给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 例:输入: nums = [1,2,...

  • 189. 旋转数组

    189. 旋转数组[https://leetcode-cn.com/problems/rotate-array/]...

  • 算法:旋转数组

    189. 旋转数组[https://leetcode-cn.com/problems/rotate-array/]...

  • 189. 轮转数组

    https://leetcode.cn/problems/rotate-array/[https://leetco...

  • 189. 轮转数组

    1.题目 给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。 示例 1:输入: nums = ...

  • 2019-01-19

    LeetCode 189. Rotate Array Description Given an array, ro...

  • [LeetCode] 189. 旋转数组

    将包含* n* 个元素的数组向右旋转 *k *步。 例如,如果 n = 7 , k = 3,给定数组 [1,...

网友评论

      本文标题:LeetCode:189. 轮转数组

      本文链接:https://www.haomeiwen.com/subject/masjkrtx.html