【每日一題-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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章