您的位置:首页 > 编程语言 > Java开发

【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:
[
[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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: