当前位置:   article > 正文

189. 轮转数组(Java)_java给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数

java给定一个整数数组 nums,将数组中的元素向右轮转 k 个位置,其中 k 是非负数

题目描述:

给定一个整数数组 nums,将数组中的元素向右轮转 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]

代码实现:

public class Main{
    public static void main(String[] args) {
        //测试案列
        int[] nums = new int[]{1, 2, 3, 4, 5, 6, 7};
        int k = 3;
        rotate(nums, k);
        System.out.println(Arrays.toString(nums));
    }

    public static void rotate(int[] nums, int k) {
        //定义一个新数组记录轮转之后的结果
        int[] arr = new int[nums.length];
        //遍历数组
        for (int i = 0; i < nums.length; i++) {
            //向右轮转k位
            arr[(i + k) % nums.length] = nums[i];
        }
        //将新数组覆盖原数组:参数(被复制数组,起始索引,覆盖数组,起始索引,覆盖长度)
        System.arraycopy(arr, 0, nums, 0, nums.length);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/567389
推荐阅读
相关标签
  

闽ICP备14008679号