计算数组中的负数

时间:2018-06-03 03:03:24

标签: java arrays multidimensional-array

我试图在2d阵列(square-matix)中找到负数的计数。在矩阵中,如果你从上到下,左边写入数字增加。这里的逻辑是从最后一列开始,然后继续向左。如果找到neg num,则增加行索引并以相同的方式继续直到最后一行。我在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 index...so j + 1
            i += 1;
        }
        else { // positive number
            j -= 1;
        }
    }
    return (count);
    }
}

我收到了这个输出

max column index is: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at O_n.count_neg(O_n.java:22)
    at O_n.main(O_n.java:9)
/home/eos/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java 
returned: 1
BUILD FAILED (total time: 0 seconds)

这段代码有什么问题?同样的事情在python ... ...

def count_neg(array):
    count = 0
    i = 0 # row
    j = len(array) -1 # col
    # since we are starting from right side

    while j >= 0 and i < len(array):
        if array[i][j] < 0: 
            count += (j + 1)
            i += 1
        else:
            j -= 1
    return count
print(count_neg([[-4,-3,-1,1],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]))

4 个答案:

答案 0 :(得分:1)

我会写这样的方法,只需要通过二维数组并在每次找到负数时增加count

public static int count_neg(int x[][]){
    int count = 0;

    for(int i = 0; i < x.length; i++){
        for(int j = 0; j < x[i].length; j++){
            if(x[i][j] < 0){
                count++;
            }
        }
    }
    return (count);
}

答案 1 :(得分:1)

您的索引与python版本相反:

while j >= 0 and i < len(array)

到Java版本:

while (i >= 0 && j < x.length)
// Change to
while (j >= 0 && i < x.length)

输出:

max column index is: 2
3

如果您使用的是Java8,则可以使用流来实现count_neg:

public static int countNeg(int x[][]) {
    long count = Stream.of(x)
            .flatMapToInt(arr -> IntStream.of(arr))
            .filter(i -> i < 0)
            .count();
    return Math.toIntExact(count);
}

答案 2 :(得分:1)

首先,您的算法无法找到负数的计数。

以下是python代码的结果:

print(count_neg([[1, 1, -1],[1, 1, -1],[1, 1, -1]])) 结果 - 9

print(count_neg([[1, 1, -1],[1, 1, 1],[1, 1, 1]])) 结果 - 3

因此,提供的代码可以找到一些负数的列索引总和+ 1,而不是全部。对于您的测试阵列,它会返回伪正确计数。

要在二维数组中找到负数的计数,您只需得到每个数字,检查一个是否小于零,如果它是真的,则将计数器增加1。因此,不可能以比O(n 2 )更好的复杂度得到正确的结果。

这里用Java做正确的代码:

public static int count_neg(int x[][]){
    int count = 0;
    for(int i = 0; i < x.length; i++){
        for(int j = 0; j < x[i].length; j++){
            if(x[i][j] < 0) count++;
        }
    }

    return count;
}

答案 3 :(得分:1)

这里使用不包含负数的列生成正确结果的算法稍有变化:

    while j >= 0 and i < len(array):
    if array[i][j] < 0:
        count += (j + 1)
        i += 1
    else:
        j -= 1
    if j < 0:
        i += 1
        j = len(array) - 1

您可以使用以下数组[[1,2,4,5],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]

对其进行测试
相关问题