【发布时间】:2016-10-03 13:03:12
【问题描述】:
我试图为 HackerRank 问题“数组:左旋转”找到更优化的解决方案,因此我将 int 基元数组转换为整数数组并使用方法 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 方法有什么问题吗?
【问题讨论】:
-
嗨,Eran,我取消删除了这个问题,感谢您编辑它。
标签: java arrays collections rotation