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

leetCode练习(74)

2016-10-16 11:10 225 查看
题目:Search a 2D Matrix

难度:medium

问题描述:

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
.

解题思路:将二维数组看成一维有序数组,然后使用二分搜索即可。b[I][j]看成一维数组的第I*row+j个。

具体代码如下:

public class m_74_SearchA2DMatrix {
public static boolean searchMatrix(int[][] matrix, int target) {
int row=matrix.length;
int column=matrix[0].length;
//使用二分搜索
int low=0;
int high=row*column-1;
int index=(low+high)/2;
int temp;
if(target>matrix[row-1][column-1]||target<matrix[0][0]){
return false;
}
while(true){
temp=getValue(matrix,column,index);
if(target<temp){
if(low==index-1){
if(getValue(matrix,column,low)==target){
return true;
}
return false;
}
high=index;
index=(low+high)/2;
continue;
}else if(target>temp){
if(high==index+1){
if(getValue(matrix,column,high)==target){
return true;
}
return false;
}
low=index;
index=(low+high)/2;
continue;
}
if(target==temp){
return true;
}
}
}
public static int getValue(int[][]matrix,int column,int index){
return matrix[index/column][index%column];
}
public static void main(String[]args){
int[][]board=new int[5][4];
int t=0;
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
board[i][j]=2*t++;
}
}
int[][] b=new int[1][2];
b[0][0]=1;b[0][1]=3;
System.out.println(searchMatrix(b,3));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode