【leetcode】74. Search a 2D Matrix
来源:互联网 发布:java格斗游戏 编辑:程序博客网 时间:2024/06/05 15:22
Difficulty:medium
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
.
这道题目其实相对在medium的难度中非常简单的一道题目,就是简单的二分搜索的变形,从一维矩阵便到了二维矩阵,但是这并不影响对二分搜索的使用。
题目中看到每一行的最后一个数字大于下一行的第一个数字,那么就可以看成第i行后顺接第i+1行,这样的话就构成了一维的矩阵。
而在操作时仅仅需要将二维转换成一维的就可以。同一维的计算相类似,设置left,right两个变量分别为0和矩阵的元素总个数-1,然后用left<=right判断循环条件,在计算mid时,需要将mid转化为二维的矩阵中的坐标,x,y
int x=mid/m;
int y=mid%m;
这样就可以用来判断matrix[x][y]与target之间的关系了。
其余部分都与一维矩阵的二分搜索相同,不再赘述。
代码如下:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int n=matrix.size(); int m=matrix[0].size(); int left,right; left=0; right=n*m-1; while(left<=right) { int mid=(left+right)/2; int x=mid/m; int y=mid%m; if(matrix[x][y]==target) return true; else if(target>matrix[x][y]) { left=mid+1; } else right=mid-1; } return false; }};
0 0
- LeetCode 74. Search a 2D Matrix
- [LeetCode]74.Search a 2D Matrix
- LeetCode --- 74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix
- [leetcode] 74.Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix
- LeetCode *** 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- LeetCode 74. Search a 2D Matrix
- leetcode-74. Search a 2D Matrix
- [leetcode] 74. Search a 2D Matrix
- 【安卓】google gsp 开发使用为了支持5.0以上的设备
- 方法(思维)的变通
- SAP ABAP程序效率优化 Perfomance Tune
- 毕业设计整理:整体思路
- hihoCoder 1234 Fractal(精度+数学题+水题)
- 【leetcode】74. Search a 2D Matrix
- __stdcall和__cdecl的区别
- Spring定时任务的写法
- 添加标签的第三方
- 在线生成InterlliJ注册码
- 从信息技术看世界发展
- 中文分词算法总结
- 如何理解C# 加载DLL的顺序
- Linux 上安装JDK(RPM版)