189. 轮转数组

2023-12-22 21:01:35

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

示例 1:

输入: 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]

示例?2:

输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释: 
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]

提示:

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 105

方法1:

    public static void rotate(int[] nums, int k) {
        int length = nums.length;
        int[] newArr = new int[length];
        k = k > length? k % length : k;
        for (int i = 0; i < nums.length; i++) {
            newArr[i] = nums[(length + i - k) % length];
        }
        System.arraycopy(newArr, 0, nums, 0, length);
    }

方法2:

    public void rotate(int[] nums, int k) {
        //翻转数组
        k = k % nums.length;
        reverse(nums,0,nums.length-1);
        reverse(nums,0,k-1);
        reverse(nums,k,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;
        }
    }

文章来源:https://blog.csdn.net/linping_wong/article/details/135160109
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。