問題描述
力扣
在一個 n * m 的二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。
解題思路:選取數組中右上角的數字。如果該數字正好等於要查找的數字,則查找過程結束;>,刪除這個數字的列;<,刪除這個數字的行。這樣縮小查找範圍,找到查找數字,或者範圍爲空,說明沒有這個數字。
解題代碼
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
boolean found = false;
int rows = matrix.length; //獲取二維數組行數
if (matrix != null && rows > 0) {
int columns = matrix[0].length; //獲取二維數組列數
int row = 0;
int column = columns - 1;
while (row < rows && column >= 0) {
if (matrix[row][column] == target) {
found = true;
break;
} else if (matrix[row][column] > target) {
column--;
} else {
row++;
}
}
}
return found;
}
}
注意:必須加上
if (matrix != null && rows > 0) //rows>0是必須的
否則會報錯:Index 0 out of bounds for length 0 ,解釋:列數=數組名[0].length這句之前要判斷數組是否爲空,若爲空則數組名[0]所代表的子數字不存在,會報錯。當 matrix 爲空時,訪問 matrix 是不會報錯的,但訪問 matrix[0] 會報錯。
時間複雜度:O(M+N),M,N爲二維數組的行數和列數,空間複雜度O(1)。