题目描述
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
解题思路
可以通过锁定一个区域减小查找的复杂度
![](https://img-blog.csdn.net/20170906184217283?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGFsYV8wMQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
public class Solution {
public boolean Find(int target, int [][] array) {
int m = array.length;
int n = array[0].length;
int line = 0;
int col1 = n-1;
int col2 =0;
boolean result = false;
if(array==null||m==0||n==0){
return false;
}else{
while(target<array[0][col1]&&col1>0){
col1 = col1-1;
}
while(target>array[m-1][col2]&&col2<n-1){
col2++;}
for(int j = 0;j<m;j++ ){
for(int col = col2;col<=col1;col++){
if(array[j][col]==target)
result = true;
}
}
return result;
}
}
}
public class Solution {
public boolean Find(int target, int [][] array) {
int m = array.length;
int n = array[0].length;
int line = 0;
int col1 = n-1;
int col2 =0;
boolean result = false;
if(array==null||m==0||n==0){
return false;
}else{
while(target<array[0][col1]&&col1>0){
col1 = col1-1;
}
while(target>array[m-1][col2]&&col2<n-1){
col2++;}
for(int j = 0;j<m;j++ ){
for(int col = col2;col<=col1;col++){
if(array[j][col]==target)
result = true;
}
}
return result;
}
}
}
注意:
- 需要考虑到数组为空时的情况,判断二维数组是否为空,不仅是array!=null这一种状况;
- 数组下标注意不要越界,特别是对下标做加减时。