剑指office------二维数组查找
题目描述:
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
问题解析:
矩阵是有序的,从左下角来看,向上数字递减,向右数字递增, 因此从左下角开始查找,当要查找数字比左下角数字大时,右移.要查找数字比左下角数字小时,上移。这样找的速度最快。
/**
* @author LanceQ
* @version 1.0 2021/4/23
*/
public class TwoDimensionalArray {
public static void main(String[] args) {
int[][] matrix={
{1, 2, 8, 9},
{2, 4, 9, 12},
{4, 7, 10, 13},
{6, 8, 11, 15}};
int value=12;
boolean b=find(matrix,value);
System.out.println(value+"是否在数组中存在:"+b);
}
private static boolean find(int[][] matrix,int value) {
int row=matrix.length-1;//行
int column=0;//列
//当行数大于0,当前列数小于总列数时循环条件成立
while(row>=0&&column<matrix[0].length){
if(matrix[row][column]<value){
column++;
}else if(matrix[row][column]>value){
row--;
}else {
return true;
}
}
return false;
}
}
运行结果
12是否在数组中存在:true
14是否在数组中存在:false
参考:https://github.com/Snailclimb/JavaGuide/blob/master/docs/dataStructures-algorithms/%E5%89%91%E6%8C%87offer%E9%83%A8%E5%88%86%E7%BC%96%E7%A8%8B%E9%A2%98.md