zoukankan      html  css  js  c++  java
  • 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;
    
    
    }
  • 相关阅读:
    2.5(他们其实都是图)
    食物链POJ1182
    LG P6748 『MdOI R3』Fallen Lord
    LG P4199 万径人踪灭
    LG P1912 [NOI2009]诗人小G
    LG P4381 [IOI2008]Island
    2020/8/9 模拟赛 T3 表格
    UOJ422 【集训队作业2018】小Z的礼物
    CF913F Strongly Connected Tournament
    LG P5643 [PKUWC2018]随机游走
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10567877.html
Copyright © 2011-2022 走看看