搜索二维矩阵

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

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

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

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

 

1.

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
var searchMatrix = function(matrix, target) {
    for(let i=0;i<matrix.length;i++){
        let left = 0;
        let right = matrix[0].length-1;
        
        if(target<=matrix[i][right]&&target>=matrix[i][left]){

            while(left<=right){
                let mid = parseInt((left+right)/2);
                if(matrix[i][mid] == target) return true;
                if(matrix[i][mid]<target) left = mid +1;
                if(matrix[i][mid]>target) right = mid -1;
            }
        }
    }
    return false;
};

2.

   var m = matrix.length;
    if(m == 0)return false;
    var n = matrix[0].length;
    var low = 0;
    var high = m*n - 1;
    while(low<=high){
        var mid = (low+high)>>1;
        var row = parseInt(mid/n);
        var col = mid%n;
        var matrixMid = matrix[row][col];
        if(matrixMid < target){
            low = mid + 1;
        }else if(matrixMid > target){
            high = mid -1;
        }else if(matrixMid == target){
            return true;
        }
    }
    return false;

来源:https://leetcode-cn.com/problems/search-a-2d-matrix/solution/74-sou-suo-er-wei-ju-zhen-by-alexer-660/

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2019-11-08 19:44  唐糖PJS  阅读(206)  评论(0编辑  收藏  举报