本文首發于我的個人部落格: 尾尾部落
題目描述
在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數
解題思路

image
二維數組是有序的,從右上角來看,向左數字遞減,向下數字遞增。
是以從右上角開始查找,
- 當要查找數字比右上角數字大時,下移;
- 當要查找數字比右上角數字小時,左移;
- 如果出了邊界,則說明二維數組中不存在該整數。
參考代碼
public class Solution {
public boolean Find(int target, int [][] array) {
if(array.length==0 || array[0].length==0)
return false;
int m = array[0].length-1;
int n = 0;
int temp = array[n][m];
while(target != temp){
if(m>0 && n<array.length-1){
if(target>temp){
n = n + 1;
}else if(target<temp){
m = m - 1;
}
temp = array[n][m];
}else{
return false;
}
}
return true;
}
}