java我的二维数组行未旋转
我试图解决二维数组行的旋转问题,下面给出了输入输出细节
在输入1之后
5 2
1 2 3 4 5
我得到了输出:-3 4 5 0 0
但预期产出为3 4 5 1 2
package geeksforgeeks.basic;
import java.util.Scanner;
public class RotationOfAnArray
{
public static void main( String[] args )
{
Scanner sc = new Scanner( System.in );
//initializing the variables and the matrix
int i, j, n, k, l, f, p;
//taking the input
n = sc.nextInt();
int[][] arr1 = new int[100][100];
for( i = 0; i < n; i++ )
{
k = sc.nextInt();
l = sc.nextInt();
for( j = 0; j < k; j++ )
{
arr1[i][j] = sc.nextInt();
}
//in the above section taking the input of the elements of the array of the matrix
for( f = 0; f < l; f++ )
{
p = arr1[0][0];
for( j = 0; j < arr1.length - 1; j++ )
{
arr1[i][j] = arr1[i][j + 1];
}
//here the row of the particular matrix is not rotated
arr1[i][arr1.length - 1] = p;
}
for( j = 0; j < k; j++ )
{
System.out.print( arr1[0][j] + " " );
}
}
}
}
# 1 楼答案
代码的问题在于,您正在将数组大小初始化为100,当稍后尝试用
arr1[i][arr1.length-1]=p;
替换最后一个元素时,它将替换最后一个99索引,而不是第4索引。若您将迭代整个数组,那个么您最终可以看到那个些值。我的建议是根据您需要的大小初始化阵列。 导入java。util。扫描仪# 2 楼答案
我认为问题在于,在遍历数组时覆盖了数组,下面是一个使用一维数组的示例