遍历每一行,然后通过二分查找算法查找
public class Solution {
public boolean Find ( int target, int [ ] [ ] array) {
for ( int i = 0 ; i < array. length; i++ ) {
if ( solve ( array[ i] , target) == 1 ) {
return true ;
}
}
return false ;
}
public int solve ( int [ ] a, int target) {
int low = 0 ;
int high = a. length;
while ( low <= high && ( low != a. length || high != a. length) ) {
int middle = ( low + high) / 2 ;
if ( target < a[ middle] ) {
high = middle - 1 ;
} else {
if ( target > a[ middle] ) {
low = middle + 1 ;
} else {
return 1 ;
}
}
}
return 0 ;
}
}
另外一种就是从最左下角开始,向上或向右
public class Solution {
public boolean Find ( int target, int [ ] [ ] array) {
int i = array. length - 1 ;
int j = 0 ;
while ( i <= array. length - 1 && i >= 0 && j >= 0 && j <= array[ 0 ] . length - 1 ) {
if ( target == array[ i] [ j] ) {
return true ;
} else {
if ( target <= array[ i] [ j] ) {
i = i - 1 ;
} else {
j = j + 1 ;
}
}
}
return false ;
}
}