【发布时间】:2015-12-05 22:58:55
【问题描述】:
我正在尝试使用一种方法将数组的元素向左移动 n(某个随机数)。困难在于将数组开头的元素与末尾的元素交换。到目前为止,这是我的代码。
问的其他数组问题与这个不同。
public class Shifty {
private int[] datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
public Shifty() {
datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
}
public int shift(int position) {
int tmp = 0;
int[] tmp1 = new int[12];
for (int i = 0; i <= 12; i++) {
if (i < position) {
tmp1[12-position] = this.datas[i];
} else {
this.datas[i] = this.datas[i+1];
}
for (int j = 12-position; j <= 12; j++){
this.datas[j] = tmp1[j];
}
}
return position;
}
public void display() {
System.out.println(Arrays.toString(this.datas));
System.out.println();
}
}
【问题讨论】:
-
您的
tmp1太小 - 至少应该是 int[13] 但 int[datqs.length] 会更健壮。在代码中直接使用12也是如此。 -
哦,错别字对不起。手机键盘不好。
-
如果你的数组是
Ineger[]而不是int[],你的解决方案可能是这个不错的单行Collections.rotate(Arrays.asList(datas), 3);。