首页 > 其他 > 详细

74. Search a 2D Matrix

时间:2019-06-22 11:24:17      阅读:91      评论:0      收藏:0      [点我收藏+]


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;

    }

74. Search a 2D Matrix

原文:https://www.cnblogs.com/reboot329/p/11067614.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!