Search a 2D Matrix

典型的二分法查找,注意循环条件是low<=high

public boolean searchMatrix(int[][] matrix, int target) {
        int row = matrix.length;
        if(row == 0)return false;
        int column = matrix[0].length;
        int count = row*column;
        int low = 0,high = count-1;
        while(low <= high){
            int middle = (low+high)/2;
            int i = middle/column;
            int j = middle%column;
            if(matrix[i][j] == target)return true;
            if(matrix[i][j] < target)low = middle+1;
            if(matrix[i][j] > target)high = middle-1;
        }
        return false;
    }


你可能感兴趣的:(Search a 2D Matrix)