search-a-2d-matrix——二维矩阵找数
题目描述
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, returntrue.
有序二维矩阵找数,先确定范围再二分查找
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 int m=matrix.size(),n=matrix[0].size(); 5 int i=0; 6 for(i=0;i<m;i++){ 7 if(target>=matrix[i][0]&&target<=matrix[i][n-1]) 8 break; 9 } 10 if(i==m) return false; 11 int left=0,right=n-1; 12 while(left<=right){ 13 int mid=(left+right)/2; 14 if(target==matrix[i][left]||target==matrix[i][right]||target==matrix[i][mid]) 15 return true; 16 if(target<matrix[i][mid]) 17 right=mid-1; 18 else 19 left=mid+1; 20 } 21 return false; 22 } 23 };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了