參考:二分查找方法
題目描述
在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
解析
方法一:劍指offer中提供的方法
如果我們從左上角開始查找,那麼當查找元素比左上元素大時,無法判斷是應該向下、向右還是向右下;從右下也是同理。
但是如果我們從右上角開始查找,當查找元素比右上元素大時,那麼第一行淘汰,只能向下;當查找元素比右上元素小時,那麼最後一列淘汰,只能向左;從左下角也是同理。
實現
bool Find(int* matrix, int rows, int columns, int number){
bool found = false;
//傳參是否有效
if(matrix==NULL || rows<=0 || columns<=0)
return found;
////從二維數組的左上角開始
//int row = 0;
//int column = columns - 1;
//while(row<rows && column>=0){
// int index = row * columns + column;
// if(matrix[index]==number){
// found = true;
// break;
// }else if(matrix[index] < number){
// row++;
// }else{
// column--;
// }
//}
//return found;
//從二維數組的右下角開始
int row = rows-1;
int column = 0;
while(row>=0 && column<columns){
int index = row * columns + column;
if(matrix[index] == number){
found = true;
break;
}else if(matrix[index] < number){
column++;
}else{
row--;
}
}
return found;
}