【leetcode】Search a 2D Matrix

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, return true.

 
最简单的想法,转化成一维的,再用二分法:
 
复制代码
 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int> > &matrix, int target) {
 4        
 5         int row=matrix.size();
 6         int col=matrix[0].size();
 7         vector<int> m(row*col);
 8        
 9         for(int i=0;i<row;i++)
10         {
11             for(int j=0;j<col;j++)
12             {
13                 m[i*col+j]=matrix[i][j];
14             }
15         }
16        
17         int left=0;
18         int right=m.size()-1;
19         int mid;
20         while(left<=right)
21         {
22             mid=(left+right)/2;
23             if(m[mid]>target)
24                 right=mid-1;
25             else if(m[mid]<target)
26                 left=mid+1;
27             else
28                 return true;
29         }
30         return false;
31        
32     }
33 };
复制代码

 

 
 
第二种思路,直接使用二分法
 
把一维数字转化为二维的坐标的方法:
第n个元素,在n/col行,n%col列
 
复制代码
 1 class Solution {
 2 public:
 3     bool searchMatrix(vector<vector<int> > &matrix, int target) {
 4        
 5         int row=matrix.size();
 6         int col=matrix[0].size();
 7        
 8         int left=0;
 9         int right=row*col-1;
10         int mid;
11         int m;
12         while(left<=right)
13         {
14             mid=(left+right)/2;
15             m=matrix[mid/col][mid%col];
16             if(m>target)
17                 right=mid-1;
18             else if(m<target)
19                 left=mid+1;
20             else
21                 return true;
22         }
23         return false;          
24     }
25 };
复制代码

 

posted @   H5开发技术  阅读(210)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示