LeetCode240. Search a 2D Matrix II

文章目录

一、题目

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

Integers in each row are sorted in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.

Example 1:

Input: 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
Output: true
Example 2:

Input: 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 = 20
Output: false

Constraints:

m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
All the integers in each row are sorted in ascending order.
All the integers in each column are sorted in ascending order.
-109 <= target <= 109

二、题解

class Solution {
   
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
   
        int m = matrix.size(),n = matrix[0].size();
        for(int i = 0;i < m;i++){
   
            int l = 0,r = n - 1;
            while(l <= r){
   
                int mid = (l + r) >> 1;
                if(matrix[i][mid] == target) return true;
                else if(matrix[i][mid] > target) r = mid - 1;
                else l = mid + 1;
            }
        }
        return false;
    }
};

相关推荐

  1. LeetCode240. Search a 2D Matrix II

    2024-01-13 04:58:02       57 阅读
  2. LeetCode|700. Search in Binary Search Tree

    2024-01-13 04:58:02       35 阅读
  3. leetcode - 1268. Search Suggestions System

    2024-01-13 04:58:02       58 阅读
  4. LeetCode79. Word Search——回溯

    2024-01-13 04:58:02       47 阅读
  5. leetcode35-Search Insert Position

    2024-01-13 04:58:02       37 阅读
  6. LeetCode //C - 704. Binary Search

    2024-01-13 04:58:02       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-13 04:58:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-13 04:58:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-13 04:58:02       82 阅读
  4. Python语言-面向对象

    2024-01-13 04:58:02       91 阅读

热门阅读

  1. Linux中RPM和yum管理和查询软件包

    2024-01-13 04:58:02       43 阅读
  2. Vue如何创建一个新页面以及相关路由配置详解

    2024-01-13 04:58:02       52 阅读
  3. 网络编程之Socket

    2024-01-13 04:58:02       59 阅读
  4. linux脚本将JAR安装进systemctl

    2024-01-13 04:58:02       54 阅读
  5. 用spring Cach在Redis中缓存数据表

    2024-01-13 04:58:02       53 阅读
  6. docker容器内运行python多进程卡住

    2024-01-13 04:58:02       52 阅读
  7. 探索跨平台UI框架Maui

    2024-01-13 04:58:02       47 阅读
  8. uni-app使用uni-ui加ts类型限制

    2024-01-13 04:58:02       52 阅读
  9. css生成

    2024-01-13 04:58:02       45 阅读