zoukankan      html  css  js  c++  java
  • 74. Search a 2D Matrix


    June-21-2019

    这个居然也没记过?

    二维转一维,用的究极二分大法,但是如果因为超左右边界而找不到。

    [[2,3,5,7],[10,11,16,20],[23,30,34,50]]  
    51
    

    yes left, no right => 找不到的话L是停在最右边超过的地方,最后判断会out of boundary..

        public boolean searchMatrix(int[][] matrix, int target) {
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
            
            int row = matrix.length;
            int col = matrix[0].length;
            if (target < matrix[0][0] || target > matrix[row - 1][col - 1]) return false;
            int l = 0, r = row * col - 1;
            
            while (l <= r) {
                int m = l + (r - l) / 2;
                int val = matrix[m / col][m % col];
                
                if (val == target) {
                    r = m - 1;
                } else if (val < target) {
                    l = m + 1;
                } else {
                    r = m - 1;
                }
            }
            
            return matrix[l / col][l % col] == target;
    
        }
    
  • 相关阅读:
    ES进阶--01
    JVM--02
    JVM--01
    ES--08
    ES--07
    ES--06
    python实现当前主机ip 主机名称的获取
    djang中的blank=True 和null = True的区别
    python中yield的用法详解
    python 编写古诗赤壁赋
  • 原文地址:https://www.cnblogs.com/reboot329/p/11067614.html
Copyright © 2011-2022 走看看