zoukankan      html  css  js  c++  java
  • Leetcode 搜索二维矩阵 II

    编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

    • 每行的元素从左到右升序排列。
    • 每列的元素从上到下升序排列。

    示例:

    现有矩阵 matrix 如下:

    [
      [1,   4,  7, 11, 15],
      [2,   5,  8, 12, 19],
      [3,   6,  9, 16, 22],
      [10, 13, 14, 17, 24],
      [18, 21, 23, 26, 30]
    ]
    

    给定 target = 5,返回 true

    给定 target = 20,返回 false

    思路:先二分target在哪一行,然后在对行进行二分找在哪一列

     1 boolean searchMatrix(int[][] matrix, int target) {
     2         if(matrix.length==0||matrix[0].length==0)
     3         {
     4             return false;
     5         }
     6         
     7         int l=0,r=matrix.length-1;
     8         int mid=0;
     9         while(l<=r)
    10         {
    11             mid=(l+r)/2;
    12             if(target==matrix[mid][0])
    13                 return true;
    14             else if(target>matrix[mid][0])
    15                 l=mid+1;
    16             else r=mid-1;
    17         }
    18         for(int i=0;i<=mid;i++)
    19         {
    20             int left=0,right=matrix[0].length-1;
    21             while(left<=right)
    22             {
    23                 int m=(left+right)/2;
    24                 if(matrix[i][m]==target)
    25                     return true;
    26                 else if(matrix[i][m]<target)
    27                     left=m+1;
    28                 else right=m-1;
    29             }
    30         }
    31         return false;
    32         
    33     }
    View Code
  • 相关阅读:
    Pigeon源码分析(一)-- 服务注册
    使用postman配置header的惨痛经历
    Redis字典知识点总结
    SpringBoot和Mybatis结合原理
    Mycat误区解释
    Mycat之常用分片规则
    Mycat之ER表划分
    模拟死锁
    生产者消费者阻塞队列
    堆排序TopK
  • 原文地址:https://www.cnblogs.com/tijie/p/9954841.html
Copyright © 2011-2022 走看看