【每日一题-leetcode】74.搜索二维矩阵

74.搜索二维矩阵

  1. 搜索二维矩阵

难度

中等

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。
  • 每行的第一个整数大于前一行的最后一个整数。

示例 1:

输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
输出: true

二分

public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return false;
        }
        //行
        int row = matrix.length;
        int clo = matrix[0].length;
        int left = 0, right = row * clo -1;
        while(left < right){
            int mid = left+(right - left)/2;
            //行->mid/clo   列->mid%clo
            if(matrix[mid/clo][mid%clo] < target){
                left = mid+1;
            }else{
                right = mid;
            }
        }
        return target == matrix[left/clo][left%clo] ? true : false;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章