5. 二维数组中的查找
问题描述:
在一个二维数组中,每一行元素都按照从左到右递增的顺序排序,每一列元素都按照从上到下递增的顺序排序。实现一个查找功能的函数,函数的输入为二维数组和一个整数,判断数组中是否含有该整数。
例子:
如果查找7 ,返回false,如果查找5,返回false。
问题分析:
假设数组 a[m][n]
, 由题意,
a[i][j]
肯定小于a[i][j+1]
~a[i][n]
,a[i][j]
肯定小于a[i+1][j]
~a[m][j]
现在我们,可以通过逐步筛选的方式来查找数据是否存在(以7为例):(蓝色代表比较的数)
为了最快的找出这个数是否存在,我们从最右上角的数出发:
为什么会从右上角出发呢?
我们从右上角开始,如果需要查找的数大于这个数,说明要查找的数一定在这一行,如果小于这个数的话,说明要查找的数一定不再这一列,由此我们得到一个新的数组,再在剩余的数组里面查找,重复以上步骤,重复直到找到这个数,或者查找完。
现在 9 > 7
, 由此我们可以得知 对应的这一列都不满足,不满足的数,我拿红色标出:
重复步骤, 8 > 7
,知道这一列都不满足,得到新的数组:
重复步骤,2 < 7
, 知道这一行都不满足,得到新数组:
重复, 4 < 7
,这一行都不满足,得到新数组:
重复比较,查找到了 7 这个数,返回true; 结束:
代码实现:
/**
* Class day05 ...
*
* @author LiJun
* Created on 2018/12/20
*/
// 二维数组中的查找
public class day05 {
public boolean find(int[][] array, int rows, int columns, int number) {
// 参数有效性检查
if (array == null || rows < 0 || columns < 0) {
System.out.println("数据错误");
return false;
}
// 查找结果,默认为false
boolean found = false;
int row = 0, column = columns - 1;
while(row < rows && column >= 0){
if(array[row][column] > number){
column--;
}else if(array[row][column] < number){
row++;
}else {
found = true;
break;
}
}
return found;
}
public static void main(String[] args) {
day05 test = new day05();
int[][] array = {
{1, 2, 8, 9, 10},
{2, 4, 9, 12, 13},
{4, 7, 10, 13, 20},
{6, 8, 11, 15, 21}
};
System.out.println(test.find(array, 4, 5, 7));
System.out.println(test.find(array, 4, 5, 5));
System.out.println(test.find(array, 4, 5, 11));
}
}
// 输出结果分别为 true false ,true
由于java中没有指针的概念,我写一下我们在c或者c++中传二维数组是传地址的方式的解决方法吧!
#include <iostream>
using namespace std;
bool find(int *array, int rows, int columns, int number) {
// 参数有效性检查
if (array == NULL || rows < 0 || columns < 0) {
cout<<"参数错误"<<endl;
return false;
}
// 查找结果,默认为false
bool found = false;
int row = 0, column = columns - 1;
while(row < rows && column > 0){
if(array[row * columns + column] > number){
column--;
}else if(array[row * columns + column] < number){
row++;
}else {
found = true;
break;
}
}
return found;
}
int main(){
int array[4][5] = {
{1, 2, 8, 9, 10},
{2, 4, 9, 12, 13},
{4, 7, 10, 13, 20},
{6, 8, 11, 15, 21}
};
cout<<find(&array[0][0], 4, 5, 7)<<endl;
cout<<find(&array[0][0], 4, 5, 11)<<endl;
cout<<find(&array[0][0], 4, 5, 22)<<endl;
return 0;
}
// 输出结果为 1 1 0