Leetcode -- Search a 2D Matrix
来源:互联网 发布:淘宝假面骑士铠武腰带 编辑:程序博客网 时间:2024/05/19 01:31
https://oj.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:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
这一题你可以考虑二分,根据行和列分成四块。
但接下来只介绍一种比较简便的做法,我们一开始就把位置定在右上角,当当前数字比target大,往下走,当前数字比target小,就往左走。这样最后要不就是找到target返回true,要不就是过界返回false。这种做法的理念貌似是和dp有关的。。当然,我还不是特别明白。。也就是,我是背答案的。。谢谢。。囧
public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length == 0 || matrix[0].length == 0) return false; int right = matrix[0].length - 1; int top = 0; while(top < matrix.length && right >= 0){ if(target > matrix[top][right]) top++; else if(target < matrix[top][right]) right--; else return true; } return false; }
0 0
- [leetcode][Search] Search a 2D Matrix
- LeetCode: Search a 2D Matrix
- LeetCode Search a 2D Matrix
- [Leetcode] Search a 2D Matrix
- LeetCode : Search a 2D Matrix
- [LeetCode] Search a 2D Matrix
- Leetcode 74 Search a 2D Matrix
- leetcode 90: Search a 2D Matrix
- [LeetCode]Search a 2D Matrix
- [Leetcode] Search a 2-D matrix
- [Leetcode]Search a 2D Matrix
- [leetcode]Search a 2D Matrix
- LeetCode-Search a 2D Matrix
- [leetcode] Search a 2D Matrix
- LeetCode - Search a 2D Matrix
- LeetCode:Search a 2D Matrix
- LeetCode 74: Search A 2D Matrix
- leetcode之Search a 2D Matrix
- 百度地图
- poj_1573
- 课程设计
- Apache HTTP Server与Tomcat集成实践
- Error LNK2001 无法解析的外部符号 的几种情况及解决办法
- Leetcode -- Search a 2D Matrix
- vim常用命令总结
- Android——动画之帧动画
- JavaScript判断浏览器类型及版本
- 学习
- jquery中的empty()与remove()区别
- Windows下使用GNU编译器
- [转]解决Codeforces访问慢的本地方案
- poj 2893 M × N Puzzle(八数码可行解)树状数组求解