leetcode 74 : Search a 2D Matrix
来源:互联网 发布:软件盒子下载 编辑:程序博客网 时间:2024/04/27 15:24
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.
代码:
方法一
利用有序矩阵的性质(行递增,列递增),从左下角往右上角搜索;比当前值小,往上搜索;比当前值大,往右搜索。从右上角往左下角搜索类似。
class Solution {public: //由于行增和列增的性质,可从左下角开始,向上递减,向右递增 //以左下为起点,往右上搜索,如果target比当前m[row][column]小,则row--,否则column++;相等返回true bool searchMatrix(vector<vector<int>>& matrix, int target) { ////提前得到size(),127个测试集,24ms->12ms int m=matrix.size(),n=matrix[0].size(); for(int row=m-1,column=0;row>=0 && column<n;){ if(target<matrix[row][column]){ row--; }else if(target>matrix[row][column]){ column++;; }else{ return true; } } return false; }};
上面代码的时间复杂度:O(m+n)
方法二
把二维矩阵看成一维数组,用二分查找
class Solution {public: //把整个矩阵看成一行,二分查找 bool searchMatrix(vector<vector<int>>& matrix, int target) { int m=matrix.size(),n=matrix[0].size(); int low=0,high=m*n-1,middle,i,j; while(low<=high){ middle=(low+high)/2; i=middle/n; j=middle%n; if(target<matrix[i][j]){ high=middle-1; }else if(target>matrix[i][j]){ low=middle+1; }else{ return true; } } return false; }};
时间复杂度:O(log(m*n)),m为行数,n为列数。
0 0
- 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
- Leetcode[74]-Search a 2D Matrix
- 【Leetcode】Search a 2D Matrix #74
- 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
- 【leetcode】【74】Search a 2D Matrix
- leetcode 74:Search a 2D Matrix
- linux远程登录管理工具
- 正确理解wait 和 notify
- struts2.xml文件详解
- box-sizing
- 第九集 经验风险最小化(ERM)
- leetcode 74 : Search a 2D Matrix
- Java多线程-线程同步(对象锁)
- eval函数的问题
- Appium 截图
- 黑马程序员——java基础——抽象类和接口
- Spring之 整合Log4j
- 【VMware】VMware linux虚拟机无法获取uuid
- UE4 学习笔记
- js中js数组、对象与json之间的转换