[LeetCode74]Search a 2D Matrix
2015-11-09 14:14
381 查看
题目来源: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:
Given target =
题目翻译: 给定一个矩阵和一个特定值, 要求写出一个高效的算法在这个矩阵中快速的找出是否这个给定的
值存在. 但是这个矩阵有以下特征.
1. 对于每一行, 数值是从左到右从小到大排列的.
2. 对于每一列, 数值是从上到下从小到大排列的.
题目解析: 对于这个给定的矩阵, 我们如果用brute force蛮力解法, 用两个嵌套循环, O(n^2)便可以得到答案.但
是我们需要注意的是这道题已经给定了这个矩阵的两个特性, 这两个特性对于提高我们算法的时间复杂度
有很大帮助, 首先我们给出一个O(n)的解法, 也就是说我们可以固定住右上角或者左下角的元素, 根据递增或者递减
的规律, 我们可以判断这个给定的数值是否存在于这个矩阵当中.
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; } else return 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; }
相关文章推荐
- 64位win&python2.7下gensim环境搭建
- 网络收集javaScript中常用的基本验证
- ADS编译问题
- SVN服务器搭建和使用(二)
- nginx+tomcat7+redis集群配置
- shell编程—— EOF
- BIEE 仪表盘的创建
- Android开发代码混淆经验(Eclipse)
- 从此不再惧怕URI编码:JavaScript及C# URI编码详解
- NFS CIFS SAMBA 的联系和区别
- ssh免密码登录 用密钥验证
- git ——映射远程分支到本地分支
- mysql忘记密码找回
- SVN服务器搭建和使用(一)
- python 多个相同字符串
- BIEE 维表
- hdoj Primes Problem 5104 (素数打表&&技巧)
- Java项目中数据库字段和用户页面显示之间的转换,比如性别字段:1显示男,0显示女
- Activity的4种launchMode
- 解决UmengSDK社会化分享过程中微信,QQ,新浪微博分享不成功的问题