Collections.rotate方法不适用于大型整数数组

时间:2016-10-03 13:03:13

标签: java arrays collections rotation

我尝试为HackerRank问题找到一个更优化的解决方案" Arrays:Left Rotation",所以我将int基元的数组转换为Integers数组并使用了Collections.rotate方法。 在第一行,用户输入 n =整数,则k =左旋转数 并且,在第二行,用户输入n个以空格分隔的整数。

但是在使用以下输入进行测试时:

61 48
431 397 149 275 556 362 852 789 601 357 516 575 670 507 127 888 284 405 806 27 495 879 976 467 342 356 908 750 769 947 425 643 754 396 653 595 108 75 347 394 935 252 683 966 553 724 629 567 93 494 693 965 328 187 728 389 70 288 509 252 449

输出结果与预期不同。 我的代码如下:

public class HackerRankArraysLeftRotationOptimized {

    public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt(); // the number of integers
    int k = in.nextInt(); // the number of left rotations you must perform
    int a[] = new int[n];
    for(int a_i=0; a_i < n; a_i++){
        a[a_i] = in.nextInt();
    }

    Integer[] newArray = new Integer[a.length];
    int i = 0;
    for (int value: a) {
        newArray[i++] = Integer.valueOf(value);
    }

    for (int j = 0; j < k; j++) {
        Collections.rotate(Arrays.asList(newArray), k);
    }

     for (int m = 0; m < newArray.length; m++) {
        System.out.print(newArray[m] + " ");
    }

}

}

有人可以解释我对方法Collections.rotate的错误吗?

1 个答案:

答案 0 :(得分:1)

Collections.rotate()向右旋转,这是第一个问题。第二个问题是你在一个循环中按k进行轮换,所以你要累计k*k次。你只需要这样做(不是循环):

Collections.rotate(Arrays.asList(newArray), -k);

相关问题