Search a 2D Matrix
来源:互联网 发布:比较丧的日剧知乎 编辑:程序博客网 时间:2024/05/16 04:39
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 和 matrix[i][j]的值. 如果小于target, 则该行不可能有此数, 所以i++; 如果大于target, 则该列不可能有此数, 所以j--. 遇到边界则表明该矩阵不含target.
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { int m = matrix.length;int n = matrix[0].length - 1;int i = 0;while (i < m && n >= 0) {<span style="white-space:pre"></span>if (target == matrix[i][n]) return true; else if (target > matrix[i][n]) {i++;}else {n--;}}return false; }}
0 0
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D Matrix
- Search a 2D matrix
- Search a 2D matrix
- 倒计时
- 区分 @NotEmpty @NotBlank @NotNull
- Using the Backup API
- ant项目构建(打jar包小案例)
- 定义文档兼容性,让IE按指定的版本解析我们的页面
- Search a 2D Matrix
- 超级强大的SVG SMIL animation动画详解
- RR信道请求/立即分配/信道释放-GSM
- 【杭电5247】*找连续数
- 【NJUST5480】Conturbatio
- 软件测试工程师未来十年的职业规划
- 第14篇 - 关于模块复用的思考
- 垃圾收集算法
- poj 2657 Comfort