在指定范围之间旋转数组中的元素 [英] Rotate an elements in an array between a specified range

查看:70
本文介绍了在指定范围之间旋转数组中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组:

int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9};

我想将数组从指定范围旋转 k 倍,即从第五个元素到最后一个元素:

And I want to rotate the array from a specified range by k times i.e. from 5th element to last element:

output: {1, 2, 3, 4, 9, 8, 5, 6, 7}

我试图使算法从数组的开始到结尾旋转

I tried to adapt the algorithm to rotate from start to end of the array

public static int[] rotate(int[] nums, int k) {
    int[] a = new int[nums.length];
    for (int i = 4; i < nums.length; i++) {
        a[(i + k) % nums.length] = nums[i];
    }
    for (int i = 4; i < nums.length; i++) {
        nums[i] = a[i + 4];
    }
    return nums;
}

但是,输出为: 1 2 3 4 0 0 5 5 7

除了将目标元素从原始数组复制到临时数组中然后运行此算法之外,我在做什么错?为什么返回 0,0 而不是 9,8 ?

Apart from copying the target elements from the original array into a temporary array and then running this algorithm, what am I doing wrong? Why is 0, 0 returned instead of 9, 8?

推荐答案

按指定步骤在指定范围之间旋转数组中的元素:

Rotate an elements in an array between a specified range by a specified step:

  1. 将数组分为三个部分:之前范围之后.

移动指定范围的数组.

2.1.将范围分为两部分: near far .

2.1. Split this range into two parts: near and far.

2.2.交换它们并串联起来.

2.2. Swap them and concatenate back.

将所有内容重新连接起来.

Concatenate everything back.

public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int[] rotated = rotateRange(arr, 4, arr.length, 3);
    System.out.println(Arrays.toString(rotated));
    // [1, 2, 3, 4, 8, 9, 5, 6, 7]
}

// rotate a specified range of an array by a specified step
static int[] rotateRange(int[] arr, int start, int end, int n) {
    return Stream.of(
            // three parts: 'before', 'range' and 'after'
            Arrays.stream(arr, 0, start),
            // get a specified range and rotate it by a specified step
            Arrays.stream(rotate(Arrays.copyOfRange(arr, start, end), n)),
            Arrays.stream(arr, end, arr.length))
            // flatten into one stream
            .flatMapToInt(Function.identity())
            // return an array
            .toArray();
}

// rotate an array by a specified step
static int[] rotate(int[] arr, int n) {
    // prevent circular rotation
    n = n % arr.length;
    return IntStream.concat(
            // concatenate the two parts: 'far' and 'near'
            Arrays.stream(arr, n, arr.length),
            Arrays.stream(arr, 0, n))
            // return an array
            .toArray();
}


另请参见:仅使用一个分号在Java中旋转int数组

这篇关于在指定范围之间旋转数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆