LeetCode Search a 2D Matrix
来源:互联网 发布:高仿充q币软件 编辑:程序博客网 时间:2024/06/07 07:21
题目链接:https://oj.leetcode.com/problems/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
.
由于这个矩阵是有序的,我们可以从右上角开始进行比较,若比右上角大,则肯定在下一行,否则就在本行中,时间复杂度O(m+n)
当然也可以用二分来做,同样从最右边那一列开始看,先二分出是在哪一行,然后再二分出是在哪一列时间复杂度 O(logn+logm)
下面给出O(m+n)的代码
class Solution {public: bool searchMatrix(vector<vector<int> > &matrix, int target) { int m=matrix.size(); int n=matrix[0].size(); if(matrix.empty()||matrix[0].empty()) return false; int x=0,y=n-1; while(x>=0&&x<m&&y>=0&&y<n) { if(matrix[x][y]==target) return true; else if(matrix[x][y]>target) y--; else x++; } return false; }};
0 0
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- 编写高质量代码——避免在构造析构函数中调用虚函数
- Windows Vista/7桌面边栏小工具开发入门
- jrtplib编程步骤文档代码解析
- QtQstring转QByteArray
- 关于sleep(0)
- LeetCode Search a 2D Matrix
- Java 加密解密 对称加密算法 非对称加密算法 MD5 BASE64 AES RSA
- QT弹出有一个提示对话框
- QT获取编辑框的内容
- iOS NSDate 时间判断
- oracle sql developer 和pl sql developer的区别
- QT添加图片资源
- POJ训练计划2503_Babelfish(二分)
- Oracle 11g 启动sql developer 时提示enter full pathname of java.exe