在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
public class Solution {
public boolean Find(int target, int [][] array) {
//數組行列數
int row = array.length;
int col = array[0].length;
//從右上角開始找
int curRow = 0;
int curCol = col - 1;
while(curRow <= row - 1 && curCol >= 0){
int value = array[curRow][curCol];
if(target == value){
return true;
}else if(target > value){//如果大於當前位置,說明在位置下面,即下一行
curRow ++;
}else{//如果小於當前位置,說明在位置左側,即上一列
curCol --;
}
}
return false;
}
}