• 74. Search a 2D Matrix(js)


    74. Search a 2D Matrix

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

    • Integers in each row are sorted from left to right.
    • The first integer of each row is greater than the last integer of the previous row.

    Example 1:

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

    Example 2:

    Input:
    matrix = [
      [1,   3,  5,  7],
      [10, 11, 16, 20],
      [23, 30, 34, 50]
    ]
    target = 13
    Output: false
    题意:给定一个s形排好序的二维数组,问我们数组中是否存在目标值target
    代码如下:
    /**
     * @param {number[][]} matrix
     * @param {number} target
     * @return {boolean}
     */
    //比较数组行的第一项,若大于target,则遍历下一行,小于target,二分法查找本行
    var searchMatrix = function(matrix, target) {
        
        
        if(matrix.length===0 || matrix===null || matrix[0].length===0) return false;
        var low=0;
        var high=matrix.length-1;
        
        while(low<=high){
            var mid=parseInt((low+high)/2);
            if(matrix[mid][0]===target) return true;
            else if(matrix[mid][0]>target) high=mid-1;
            else low=mid+1;
        }
        //找到可能存在target行
        var row=high;
        if(row<0) return false;
        
        low=0;
        high=matrix[0].length-1;
        while(low<=high){
            var mid=parseInt((low+high)/2);
            if(matrix[row][mid]===target) return true;
            else if(matrix[row][mid]>target) high=mid-1;
            else low=mid+1;
        }
        return false;
    
    
    }
  • 相关阅读:
    记录:VC++中打开保存目录选择对话框操作
    Active Server Pages 错误 ASP 0201 的最终解决办法
    已经阅读过的Ajax文章资源
    Delphi编译/链接过程
    初探Object Pascal的类(四)
    初探Object Pascal的类(九)
    初探Object Pascal的类(十)
    初探Object Pascal的类(五)
    初探Object Pascal的类(八)
    Delphi 7 IDE 界面
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10567877.html
Copyright © 2020-2023  润新知