[leetcode]240. Search a 2D Matrix II
来源:互联网 发布:https seo 编辑:程序博客网 时间:2024/06/06 03:44
题目链接:https://leetcode.com/problems/search-a-2d-matrix-ii/#/description
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
.
思路:从右上角开始遍历,如果matrix[ i ][ j ]<target, 说明该行所有的数都小于target, 则i++ 。如果matrix[ i ][ j ]>target,说明该列所有的数都大于target,则j--。
class Solution{public: bool searchMatrix(vector<vector<int>>& matrix,int target) { if (matrix.size()==0 || matrix[0].size()==0) return false; int rowNum=matrix.size(); int colNum=matrix[0].size(); int i=0,j=colNum-1; while(i<rowNum && j>-1) { if(target==matrix[i][j]) { return true; } else if(target>matrix[i][j]) { i++; } else if(target<matrix[i][j]) { j--; } } 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
- 广告行业PMP
- 颜色、像素、帧缓存
- MPAndroidChart之LineChart双线绘制
- cocos2dx-3.6 开发技巧(二)回调函数以及动画的使用,触摸事件,android返回键,屏幕截屏
- 使用printf 打印数据的一个小小疑问,待解!
- [leetcode]240. Search a 2D Matrix II
- ubuntu和win10双系统安装教程
- node-sass报错解决方法
- 关于使用ExcelEngine在Windows中编译的补充
- KVC-KVO
- 常用的后端命令 【笔记】
- 自定义控件时使用setTextSize出现的问题
- 符号链接与设备接口名
- CuratorFramework实现zookeeper文件夹与文件的上传下载