已知一个按行和按列都是增序的数字矩阵,如何快速查找某个数x是否在矩阵中?
思路其实比较简单,只要利用好第一排的数比第二排对应位置的数小,第一列的数比第二列对应位置的数小这一规律就行。
/**
* 快速在一个按行和按列都是增序的数字矩阵查找某个数
*
* @author cui
*
*/
public class MatrixSelect {
public static void main(String[] args) {
int[][] input = {
{ 1, 4, 7, 11, 15 },
{ 2, 5, 8, 12, 19 },
{ 3, 6, 9, 16, 22 },
{ 10, 13, 14, 17, 24 },
{ 18, 21, 23, 26, 30 }
};
select(input,1);//found 1 in (0,0)
select(input,5);//found 5 in (1,1)
select(input,17);//found 17 in (3,3)
select(input,30);//found 30 in (4,4)
select(input,-1);//not found -1
select(input,20);//not found 20
select(input,50);//not found 50
}
public static void select(int[][] m, int target) {
int row = 0, col = m[0].length-1;
while (col >= 0 && row < m.length) {
int cur=m[row][col];
if(cur==target){
System.out.println("found " + target+" in ("+row+","+col+")");
return;
}else if(cur>target){
col--;
}else if(cur<target){
row++;
}
}
System.out.println("not found " + target);
}
}