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;
    
    
    }
  • 相关阅读:
    跨域
    reactV16理解
    css动画总结
    h5与app交互
    跨域
    ant-design如果按需加载组件
    移动端300ms延迟原理,穿透、遮罩层滑动导致下面滑动总结
    监听数组的变化
    使用VS Code调试Node.js
    React-typescript-antd 常见问题
  • 原文地址:https://www.cnblogs.com/xingguozhiming/p/10567877.html
Copyright © 2011-2022 走看看