[LeetCode74]Search a 2D Matrix
来源:互联网 发布:sql日期取年月日 编辑:程序博客网 时间:2024/06/05 22:50
题目来源:https://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
.
值存在. 但是这个矩阵有以下特征.
1. 对于每一行, 数值是从左到右从小到大排列的.
2. 对于每一列, 数值是从上到下从小到大排列的.
题目解析: 对于这个给定的矩阵, 我们如果用brute force蛮力解法, 用两个嵌套循环, O(n^2)便可以得到答案.但
是我们需要注意的是这道题已经给定了这个矩阵的两个特性, 这两个特性对于提高我们算法的时间复杂度
有很大帮助, 首先我们给出一个O(n)的解法, 也就是说我们可以固定住右上角或者左下角的元素, 根据递增或者递减
的规律, 我们可以判断这个给定的数值是否存在于这个矩阵当中.
class Solution74{public:bool searchMatrix(vector<vector<int>> &matrix, int target){/*数组为0,return false*/if (matrix.size() == 0){return false;}if (matrix[0].size() == 0){return false;}int row = matrix.size()-1;int col = 0;while (row >= 0 && col < matrix[0].size()){if (target < matrix[row][col]){--row;}else if (target > matrix[row][col]){++col;}elsereturn true;}return false;}};int main(){Solution74 solution;{vector < vector < int > > vec = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };int target = 21;if (solution.searchMatrix(vec, target)){cout << "true" << endl;}else{cout << "false";}}system("pause");return 0;}
0 0
- [LeetCode74]Search a 2D Matrix
- [LeetCode74]Search a 2D Matrix
- Leetcode74. Search a 2D Matrix
- leetcode74. Search a 2D Matrix
- LeetCode74 Search a 2D Matrix
- LeetCode74——Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- nginx+tomcat7+redis集群配置
- 网络收集javaScript中常用的基本验证
- SVN服务器搭建和使用(二)
- Unix学习笔记------书本例题编程实例------从标注输入读入然后从标准输出输出
- 64位win&python2.7下gensim环境搭建
- [LeetCode74]Search a 2D Matrix
- android 文件缓存 字符串
- Communicating between views in Backbone
- 子类与父类,以及子类的继承,重载与重写。
- 支付宝SDK下载页面
- Android开源项目分包方式学习
- VS2010快捷键
- android中java.lang.IllegalStateException异常产生的原因及解决办法
- displaytag.properties