我正在尝试查找二维数组(平方矩阵)中负数的计数。在矩阵中,如果您从上到下然后向左写,则写数增加。此处的逻辑是从最后一列开始,然后向左进行。如果找到负数,则增加行索引,并以相同的方式进行操作,直到最后一行。我在Java代码中收到错误,但在python中却没有。
public class O_n
{
public static void main(String[] args)
{
int firstarray[][] = {{-2,-1,0},{-1,0,1},{0,1,2}};
int secondarray[][] = {{-4,-3,-2},{-3,-2,-1},{-2,-1,0}};
System.out.print ("First array has"+count_neg(firstarray));
System.out.println("negative numbers");
System.out.print ("Second array has"+count_neg(secondarray));
System.out.println("negative numbers");
}
public static int count_neg(int x[][]){
int count = 0;
int i = 0; //rows
int j = x.length - 1; //columns
System.out.println("max column index is: "+j);
while ( i >=0 && j<x.length){
if (x[i][j] < 0){ // negative number
count += (j + 1);// since j is an …Run Code Online (Sandbox Code Playgroud)