美文网首页
Search a 2D Matrix

Search a 2D Matrix

作者: Wenyue_offer | 来源:发表于2017-09-14 02:10 被阅读0次
public static boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0) return false;
        int m = matrix.length, n = matrix[0].length;
        int left = 0, right = m * n - 1;
        while(left <= right) 
        { 
            int middle = left + (right - left) / 2; 
            int i = middle / n; 
            int j = middle % n; 
            if(matrix[i][j] == target) return true; 
            else if(matrix[i][j] > target) right = middle - 1;
            else left = middle + 1;
        }
        return false;
    }

相关文章

网友评论

      本文标题:Search a 2D Matrix

      本文链接:https://www.haomeiwen.com/subject/wqjrsxtx.html