leetcode Search a 2D Matrix II
来源:互联网 发布:it wizardry 编辑:程序博客网 时间:2024/06/04 04:32
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
.
据说是一道很经典的题目,许多大公司面试都有考到,我一开始的思路是从左上角开始比较,如果target小于该值则返回false,若大于则递归查询右边的矩阵和下边的矩阵,但是传上去后出现TLE,想了半天没想到好办法,上网查了一下,思路是这样的:从右上角开始比较,若target大于该值,说明该行不存在target,行数+1,若target小于该值,说明该列不存在target,列数-1,代码如下:
public boolean searchMatrix(int[][] matrix, int target) { int i=0; int j=matrix[0].length; while(i<matrix.length&&j>=0) { if(matrix[i][j]==target) return true; else if(matrix[i][j]<target){ ++i; } else if(matrix[i][j]>target){ --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
- 面试干货!21个必知数据科学面试题和答案part1(1-11)
- python爬虫(一)
- Android产品研发(十八)-->webview问题集锦
- 面试干货!21个必知数据科学面试题和答案part2(12-21)
- NI/NDK Develop Guide (3) Handle String
- leetcode Search a 2D Matrix II
- 游戏类实例为null
- 【音乐拼接】mp3格式
- 护照阅读机 护照阅读器 护照识别仪 护照扫描仪 护照扫描机 电子护照阅读器 电子护照阅器一体机 护照批量录入 护照录入 护照识别 护照管理
- 【2003】找出数列中的最小数,把它与数列的第一个数对调。
- 【2004】数学黑洞数6174
- 消除游戏的核心算法
- 干渠电站调压阀(空放阀)加工出现问题
- iOS 获取当月最后一天或获取当月共有多少天