74. Search a 2D Matrix
来源:互联网 发布:淘宝上传宝贝失败 编辑:程序博客网 时间:2024/06/03 19:50
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
.这道题思路比较简单,就是二分查找,首先确定范围,然后针对具体的一行进行二分查找就可以啦,代码如下:
public boolean searchMatrix(int[][] matrix, int target) {
boolean flag = false;
// 特殊情况处理
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
// 找到target所在的行
int row = matrix.length;
int col = matrix[0].length;
for(int i = 0; i < row; i++){
if(target <= matrix[i][col - 1]){
flag = binarySearch(i, matrix, target);
break;
}
}
return flag;
}
private boolean binarySearch(int row, int[][] matrix, int target){
int left = 0, right = matrix[0].length - 1;
while(left < right){
int mid = (left + right) / 2;
if(matrix[row][mid] == target){
return true;
}else if(matrix[row][mid] < target){
left = mid + 1;
}else{
right = mid - 1;
}
}
if(matrix[row][left] == target){
return true;
}else{
return false;
}
}
- LeetCode 74. Search a 2D Matrix
- [LeetCode]74.Search a 2D Matrix
- LeetCode --- 74. Search a 2D Matrix
- [Leetcode] 74. Search a 2D Matrix
- [leetcode] 74.Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- Leetcode 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix LeetCode
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- [LeetCode]74. Search a 2D Matrix
- 74. Search a 2D Matrix
- 74. Search a 2D Matrix
- leetcode 74. Search a 2D Matrix
- 二分法解决打印所有和为s的连续整数序列 剑指offer 之 面试题41_2
- 魅力物理2
- 安装Android Studio 可能遇到的问题及解决办法
- 基础查询
- 杭电OJ 2009.求数列的和
- 74. Search a 2D Matrix
- poj Wireless Network(基础并查集)
- 使用JDK开发WebService-客户端建立
- 使用TOP查询
- uva 10334Ray Through Glasses
- RTMP学习(八)rtmpdump源码阅读(3)初始化与URL解析
- leecode 解题总结:324. Wiggle Sort II
- (1)第一次产品面试的感受
- Android面试题集