Skip to content

Latest commit

 

History

History
39 lines (34 loc) · 1.14 KB

二维数组的查找.md

File metadata and controls

39 lines (34 loc) · 1.14 KB

####二维数组的查找

在一个二维数组中,每一行都按照从左到右递增的顺序,每一列都按照从上到下递增的顺序排序。请完成这样一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。

package lintcode;
public class FindNumber {
    public static boolean findNumber(int[][] a, int n) {
        if (a.length == 0) {
            return false;
    }

    boolean found = false;
    int rows = a.length;
    int columns = a[0].length;
    int row = 0, column = columns - 1;

    while (row < rows && columns > 0) {
        if (a[row][column] == n) {
            found = true;
            break;
        } else if (a[row][column] < n) {
            ++row;
        } else {
            --column;
        }
    }

    return found;
}

public static void main(String[] args) {
    int[][] a = {{1, 2, 8, 9},
            {2, 4, 9, 12},
            {4, 7, 10, 13},
            {6, 8, 11, 15}};
    boolean ret = findNumber(a, 7);
    System.out.println(ret);
}

}