题意:给出一个二维矩阵,每行、每列都递增排序。查找这个矩阵中的某个数,看是否存在。
思路:每次看最右上角的数,若和待查找的数相等,则返回;若是大于目标数,则将矩阵中的该列删除;若是小于目标数,则将矩阵中的该行删除。同样,也可每次看最左下角的数字。
代码:
package MianShiTi_3;
public class MianShiTi_3 {
//从最右上角开始查找
public boolean Find(int [][]matrix ,int target){
int rows = matrix.length;
int columns = matrix[0].length;
boolean find = false;
if(matrix != null && rows > 0 && columns > 0){
int row = 0;
int column = columns -1;
while (row < rows && column >=0) {
if(matrix[row][column] == target){
find = true;
break;
}else if (matrix[row][column] > target) {
column -- ;
}else {
row++;
}
}
}
return find;
}
//从最左下角开始查找
public String Find2(int [][]matrix ,int target){
int rows = matrix.length;
int columns = matrix[0].length;
String s1 = "bingo";
String s2 = "foolish";
if(matrix != null && rows > 0 && columns >0){
int row = rows - 1;
int column = 0;
while (column < columns && row >=0) {
if(matrix[row][column] == target){
return s1;
}else if (matrix[row][column] < target) {
column++;
}else {
row--;
}
}
}
return s2;
}
public static void main(String[] args) {
int [][]matrix = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
boolean Find = false;
int target1 = 1;
int target2 = 100;
Find = new MianShiTi_3().Find(matrix, target1);
System.out.println(Find);
System.out.println(new MianShiTi_3().Find2(matrix, target2));
}
}