Search a 2D Matrix
来源:互联网 发布:原生js获取input框 编辑:程序博客网 时间:2024/06/11 16:48
Q:
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
.
Solution:
Time is O(m+n).
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0 || matrix[0].length == 0 || matrix[0][0] > target) return false; int m = matrix.length; int n = matrix[0].length; int column = -1; if (matrix[m-1][0] <= target) column = m-1; else { int top = 0; int bottom = m - 1; while (top <= bottom) { int mid = (top + bottom) / 2; if (matrix[mid][0] == target) return true; if (matrix[mid][0] < target && matrix[mid+1][0] > target) { column = mid; break; } if (matrix[mid][0] > target) bottom = mid - 1; else top = mid + 1; } } int left = 0; int right = matrix[0].length - 1; int row = 0; while (left <= right) { row = (left + right) / 2; if (matrix[column][row] == target) return true; if (matrix[column][row] > target) right = row - 1; else left = row + 1; } 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
- 内核模块运行在哪
- 360公司2015年秋季校园招聘笔试考卷(技术类 D)部分试题程序验证和解析6
- Memory Analyzer tool(MAT)
- Lua学习之2 :Lua调用C++函数
- linux用户权限和文件权限
- Search a 2D Matrix
- 大数据在传统行业引爆后如何落地
- hdu 4950 打怪
- 搞了一天终于稍微成功在github上搭了个博客...
- Oulipo (poj 3461&&hdu 1686) KMP
- Least Common Ancestors
- 第八周项目1:分段函数求值
- ADFS部署过程中设置network service对证书的读取权限
- hdu 5014 Number Sequence 2014 ACM/ICPC Asia Regional Xi'an Online