给定一个整数数组和一个数字,我需要对数组执行左旋转,并返回更新后的数组,以单行空格分隔的整数形式打印。 我通过了 7/9 检查,但一些大型数组由于超时而失败。
时间必须 <= 4 秒。
static int[] rotLeft(int[] a, int d) {
int x = 0;
while (x != d) {
int first = a[0];
int last = a[a.length - 1];
for (int i = 0; i < a.length - 1; i++) {
a[i] = a[i + 1];
if (i == a.length - 2)
a[a.length - 2] = last;
a[a.length - 1] = first;
}
x++;
}
return a;
}
最佳答案
一次只旋转一个位置,速度很慢,最好将元素移动到适当的位置,例如:
static int[] rotLeft(int[] a, int d) {
if (d == 0 || a == null || a.length == 0) {
return a;
}
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = a[(i + d) % a.length];
}
return b;
}
关于java - Java中的数组左旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60877555/