LeetCode 240. Search a 2D Matrix II
来源:互联网 发布:网络综合布线公司 编辑:程序博客网 时间:2024/06/06 04:42
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]]
Given target = 5
, return true
.
Given target = 20
, return false
.
m x n矩阵中,每一行和每一列都是从小到大排列,要求判断一个值是否属于该矩阵。
解决思路:从右上角或从左下角的元素开始搜索。以右上角为例:
如果元素的值等于target,则返回true;
如果元素的值小于target,则应该搜索左边的元素;
如果元素的值大于target,则应当搜索下面的元素;
当左边或者下面没有元素的时候,结束循环,返回false。
代码实现如下:
class Solution {public:bool searchMatrix(vector< vector<int> >& matrix, int target) {if(matrix.size()==0 || matrix[0].size()==0) return false; int m=0, n=matrix[0].size()-1; while(m<matrix.size() && n>=0) { int x = matrix[m][n]; if(target == x) return true; else if(target < x) --n; else ++m; } return false; }};
0 0
- #leetcode#Search a 2D Matrix II
- [LeetCode] Search a 2D Matrix II
- leetcode: Search a 2D Matrix II
- leetcode - Search a 2D Matrix II
- [leetcode] Search a 2D Matrix II
- 【leetcode】Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [Leetcode]Search a 2D Matrix II
- [LeetCode]Search a 2D Matrix II
- LeetCode Search a 2D Matrix II
- [LeetCode]Search a 2D Matrix II
- LeetCode || Search a 2D Matrix II
- LeetCode----Search a 2D Matrix II
- Leetcode: Search a 2D Matrix II
- *LeetCode-Search a 2D Matrix II
- Search a 2D Matrix II -- leetcode
- leetcode | Search a 2D Matrix II
- CSS3形变——transform与transform-origin画时钟
- Spring Security 配置类实现(2)
- React 笔记
- Java并发学习1
- Houston, we have a problem
- LeetCode 240. Search a 2D Matrix II
- 聊一聊C语言变量
- inode 等待dio完成
- centos7 安装python-pip及python的第三方库
- 应用层
- ftp连接报错:Windows无法访问此文件夹
- 微信小程序开发中常用的功能代码分享
- C#图像处理(各种旋转、改变大小、柔化、锐化、雾化、底片、浮雕、黑白、滤镜效果)
- win32使用Qt和libmodbus库实现modbus主机功能