【leetcode】第74题 Search a 2D Matrix 题目+解析+JAVA代码
2017-09-11 18:18
537 查看
【题目】
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:
Given target =
【解析】
这道题给了一个排好序的二维矩阵,问改矩阵内是否有target这个数字。其实不用把它当成矩阵,直接按照一个序列来计算即可。
【代码】
public boolean searchMatrix(int[][] matrix, int target) {
int m=matrix.length;
if(m==0) return false;
int n = matrix[0].length;
int left=0,right=m*n-1;
while(left<=right){
int mid=(left+right)/2;
if(target==matrix[mid/n][mid%n])
return true;
else if(target>matrix[mid/n][mid%n])
left=mid+1;
else
right=mid-1;
}
return false;
}
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这个数字。其实不用把它当成矩阵,直接按照一个序列来计算即可。
【代码】
public boolean searchMatrix(int[][] matrix, int target) {
int m=matrix.length;
if(m==0) return false;
int n = matrix[0].length;
int left=0,right=m*n-1;
while(left<=right){
int mid=(left+right)/2;
if(target==matrix[mid/n][mid%n])
return true;
else if(target>matrix[mid/n][mid%n])
left=mid+1;
else
right=mid-1;
}
return false;
}
相关文章推荐
- 【leetcode】第73题 Set Matrix Zeroes 题目+解析+JAVA代码
- leetcode:Search a 2D Matrix 【Java】
- LeetCode算法题目:Search a 2D Matrix
- leetcode 第74题 Search a 2D Matrix
- 【leetcode】第59题 Spiral Matrix II 题目+解析+代码
- [LeetCode][Java] Search a 2D Matrix
- 【Leetcode】Search a 2D Matrix in JAVA
- 【leetcode】第66题 Plus One 题目+解析+JAVA代码
- 【leetcode】第67题 Add Binary 题目+解析+JAVA代码
- leetcode解题之 Search a 2D Matrix java 版(在二维矩阵中查找)
- 【leetcode】第62题 Unique Paths 题目+解析+JAVA代码
- 【leetcode】74. Search a 2D Matrix【java】
- [Leetcode] Search a 2D Matrix (Java)
- 【leetcode】第63题 Unique Paths II 题目+解析+JAVA代码
- (java)leetcode74:Search a 2D Matrix
- LeetCode – Search a 2D Matrix (Java)
- leetcode 240 Search a 2D Matrix II java 算法
- leetcode JAVA Search a 2D Matrix 难度系数3 3.25
- LeetCode 74 Search a 2D Matrix with java solution
- 【LeetCode-面试算法经典-Java实现】【074-Search a 2D Matrix(搜索二维矩阵)】