前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[LeetCode] 74. Search a 2D Matrix

[LeetCode] 74. Search a 2D Matrix

作者头像
用户1148830
发布2018-01-03 17:41:43
4310
发布2018-01-03 17:41:43
举报

【原题】

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.

For example,

Consider the following matrix:

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

Given target = 3, return true. 【解释】 给定一个二维数组每一行有序,行与行之间有序,给定一个target,要求返回该元素是否在二维数组中。 【思路】 有序自然想到二分查找。但这题需要使用两次二分查找,首先二分查找到行,然后在该行中再使用二分(刚开始,使用顺序查找得到行号也可以过)。假设二维矩阵为mxn,则算法的复杂度为O(logm+logn)O(logm+logn).

代码语言:javascript
复制
public class Solution {
//查找列
        public boolean binarySearchCol(int[][] matrix, int row, int target){
        int left=0,right=matrix[row].length-1;
        while(left<right){
            int mid=(left+right)/2;
            if(matrix[row][mid]==target)
                return true;
            if(matrix[row][mid]>target)
                right=mid-1;
            else 
                left=mid+1;
        }
        return matrix[row][left]==target;
    }
    public boolean searchMatrix(int[][] matrix, int target) {
        int m=matrix.length;
        if(m==0) return false;
        int n=matrix[0].length;
        if(n==0) return false;
        int left=0,right=m-1;
        /*注意这个二分查找要找到可能在的行,所以没有找到对应的target不能直接返回false,
        而要在最可能的一行单重继续查找*/
        while(left<right){
            int mid=(left+right+1)/2;
            if(matrix[mid][0]>target)
                right=mid-1;
            else if(matrix[mid][0]<target)
                left=mid;
            else return true;        
        }
       return  binarySearchCol(matrix, left,target);   
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年06月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档