LeetCode刷题(C++)——Search a 2D Matrix(Medium)
来源:互联网 发布:开源bug系统 java 编辑:程序博客网 时间:2024/06/04 18:50
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:每次和矩阵的右上角元素进行比较。设右上角元素为y,要查找的元素为x,则
(1)当x<y时,则第一行所有的元素都小于y,可以删掉;
(2)当x>y时,则最后一列所有的元素都大于y,可以删掉;
如此循环比较,直到找到x或者矩阵元素为空。这样每次都能删掉一行或者一列,缩小查找范围。时间复杂度为O(m+n)=O(max(m,n))
代码实现如下:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) { if(matrix.empty()) return false; int m = matrix.size(), n = matrix[0].size(); for(int i=0, j=n-1; (i<m)&&(j>=0);){ if(matrix[i][j] == target) return true; else if(matrix[i][j] > target) --j; else ++i; } return false; }};思路2:分治思想
取矩阵的中心点元素x和查找的元素y 进行比较,如图
(1)如果x<y,则y不可能在A中,可以删除;
(2)如果x>y,则y不可能在D中,可以删除;
时间复杂度不容易分析出来,大概在O(n^0.5)~O(n)之间
代码如下:
class Solution {public: bool searchMatrix(vector<vector<int>>& matrix, int target) {if (matrix.empty())return false;int m = matrix.size(), n = matrix[0].size();return find(matrix, 0, 0, m - 1, n - 1, target);}bool find(vector<vector<int>> &a, int x1, int y1, int x2, int y2, int target) {if ((x1 > x2) || (y1 > y2))return false;int midx = (x1 + x2) >> 1;int midy = (y1 + y2) >> 1;if (a[midx][midy] == target)return true;return (target < a[midx][midy]) ?(find(a, x1, y1, midx - 1, y2, target) || find(a, midx, y1, x2, midy - 1, target)) :(find(a, x1, midy + 1, x2, y2, target) || find(a, midx + 1, y1, x2, midy, target));}};
1 0
- LeetCode刷题(C++)——Search a 2D Matrix(Medium)
- 题解——Leetcode 240. Search a 2D Matrix II 难度:Medium
- LeetCode 之 Search a 2D Matrix — C 实现
- [Leetcode 74, medium] Search a 2D Matrix
- [Leetcode 240, Medium] Search a 2D Matrix II
- 【LeetCode】7(4)Search a 2D Matrix(Medium)
- 【LeetCode】(240)Search a 2D Matrix II(Medium)
- LeetCode-74-Search a 2D Matrix(二分查找)-Medium
- Leetcode 74. Search a 2D Matrix (Medium) (cpp)
- Leetcode 240. Search a 2D Matrix II (Medium) (cpp)
- 【LeetCode】240. Search a 2D Matrix II (Medium)
- Leetcode 240. Search a 2D Matrix II[medium]
- Search a 2D Matrix(medium)
- Medium:Search a 2D Matrix II
- LeetCode刷题(40)--Search a 2D Matrix
- leetcode——Search a 2D Matrix 二维有序数组查找(AC)
- Search a 2D Matrix ——Leetcode系列(十八)
- 【leetcode】Array——Search a 2D Matrix(74)
- centos7安装mysql-5.7.18-1.el7.x86_64.rpm-bundle.tar
- java-Selenium-Page Object设计模式思路
- Python学习之生成式的send()详解
- STM32之USART 232串口通信<一>
- 汉诺塔问题
- LeetCode刷题(C++)——Search a 2D Matrix(Medium)
- 经典算法之传染病问题
- onino病毒来袭,教你快速关闭某端口
- 经典算法之八皇后问题
- 021-将镜像推送到 Docker Hub
- 解决Mysql不在电脑服务列表中的问题
- Synchronized及其实现原理
- 数据结构之树
- USACO