Leetcode解题报告:74. Search a 2D Matrix
来源:互联网 发布:影视后期 知乎 编辑:程序博客网 时间:2024/06/05 23:03
题目大意:
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.
难度:Medium
解题思路: 由于这道题中,第 i+1 行的所有元素比第i行都大, 我们可以把这个二维数组简化为一个有序的一维数组。 在二维数组中,一个元素的行列坐标记为x,y,每行的元素个数记为n,行的数目记为m,那么在一维数组中,该元素对应的下标就是x*n+y,在一维数组中,元素按照大小已经排好序了,那么我们可以采取二分查找的方式寻找目标值。 取中间位置的元素为pivot,如果目标值就是这个元素,就返回true。如果目标值比pivot小,就用同样的方法搜索下标比pivot下标小的区间,如果比pivot大,就搜索下标大于pivot下标的区间,直到搜索到目标值返回true,或者区间的起始下标大于终点下标就可以认为数组中没有目标值。
具体操作中,我们可以从起始下标0,终止下标为数组的行数*数组的列数-1作为终点下标开始按照如上的思想递归地进行搜索,中间位置mid=(start+end)/2, 在二维数组中对应的位置为(mid/n,mid%n)其中n是每行的元素个数。
这种方法的时间复杂度就是二分查找的时间复杂度,O(logn)
class Solution {public:bool helper(vector<vector<int>>& nums,int start,int end,int target){int mid=(start+end)/2;int x=mid/nums[0].size();int y=mid%nums[0].size();if(start>end)return false;if(nums[x][y]==target){return true;}else if(nums[x][y]>target){return helper(nums,start,mid-1,target);}elsereturn helper(nums,mid+1,end,target);}bool searchMatrix(vector<vector<int>>& matrix, int target) {if(matrix.size()==0)return false; else returnhelper(matrix,0,matrix[0].size()*matrix.size()-1,target); }};
0 0
- [leetcode] 74. Search a 2D Matrix 解题报告
- Leetcode解题报告:74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix 解题报告
- [leetcode] 240. Search a 2D Matrix II 解题报告
- leetcode解题报告:240. Search a 2D Matrix II
- LeetCode 240. Search a 2D Matrix II 解题报告
- [Leetcode] 240. Search a 2D Matrix II 解题报告
- Leetcode 74. Search a 2D Matrix 2D矩阵查找 解题报告
- Search a 2D Matrix 解题报告
- Search a 2D Matrix II 解题报告
- 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
- Java并发 可见性 理解
- 每天一个小程序——第 0001 题:生成200个验证码
- 十进制二进制转换
- MySQL安全配置向导mysql_secure_installation
- $.trim(str)、$.get()、$.post()、$.ajax()
- Leetcode解题报告:74. Search a 2D Matrix
- c++文件的相互包含问题
- 使用idea Live Template实现eclipse syso自动提示代码功能
- 在文本框中显示获取选择上传多个文件的名称
- 织梦CMS自定义模板图片调用
- java并发编程:创建线程和进程
- [OpenStack-Nova]宿主机重启自动恢复虚拟机运行状态
- nginx搭建rtmp协议流媒体服务器总结
- virtualenv