在行式和列式 N x M 排序矩阵中搜索

Search in a row wise and column wise N x M sorted matrix

给定一个由大小为 N x M 的整数 A 和一个整数 B 组成的矩阵。 在给定的矩阵中,每一行和每一列都按升序排列。找到并 return B 在给定形式的矩阵中的位置:

  1. 如果 A[i][j] = B 则 return (i * 1009 + j)
  2. 如果 B 不存在 return -1.

我的解决方案:

    public static int solve(int[][] A, int B) {
    int N = A.length;
    int i = 0;
    int j = N - 1;
    while (i < N && j >= 0) {
        if (A[i][j] == B) {
            System.out.println("number found");
            return (i * 1009 + j);
        }
        if (A[i][j] > B) {
            j--;
        } else {
            i++;
        }
    }
    System.out.println("number not found");
    return (-1);
}

当矩阵不是 NxN 时不起作用。我该如何解决?

j的索引应该是有效的,否则它不适用于N X M矩阵

int j = A[0].length - 1;