我在尝试解决一个练习时遇到了问题
编写一个移动程序,使列表旋转几次(第一个元素变为最后一个)。
list = 1,2,3,4,5 and N = 2 -> result = 3,4,5,1,2
请注意,N可能大于列表的长度,在这种情况下,您将旋转列表几次。
list = 1,2,3,4,5 and N = 6 -> result = 2,3,4,5,1
输入在第一行,您将收到号码列表。在第二行,您将收到N
输出在输出的唯一一行,打印用空格分隔的数字。
以下是测试:
测试1:
输入5,3,2,1 2
输出2,1,3,3
测试2:
输入2,1,3,4 5
输出1,3,4,2
这是我迄今为止的代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] elements = input.split(",");
int[] array = new int[elements.length];
for (int i = 0; i < elements.length; i++) {
array[i] = Integer.parseInt(elements[i]);
}
int a = scanner.nextInt();
int[] rotated = new int[elements.length];
for (int x = 0; x <= array.length - 1; x++) {
rotated[(x + a) % array.length] = array[x];
}
for (int i = 0; i < rotated.length; i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(rotated[i]);
}
}
}
第一次测试通过。但是第二个测试没有通过,我的程序给了我错误的输出:4,2,1,3,而不是正确的输出:1,3,4,2。
我搞不清问题出在哪里。
提前感谢您的帮助。
您的逻辑可以简化为:
public static void shiftLeft(int shiftBy, int arr[]) {
for (int j = 0; j < shiftBy; j++) {
int a = arr[0]; // storing the first index
int i;
for (i = 0; i < arr.length - 1; i++) { // shifting the array left
arr[i] = arr[i + 1];
}
arr[i] = a; // placing first index at the end
}
}
现在称之为:
public static void main(String[] args) {
// Fetch all data from user as you have done
int arr[] = { 1, 2, 3, 4, 5 };
shiftLeft(n % arr.length, arr);
// print out the array
}
请注意,如果数字n
大于数组的长度,则实际上不必将其移位那么多次。相反,您只需要将其移动n % arr.length
次。