題目
在一個 n * m 的二維陣列中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序,請完成一個函式,輸入這樣的一個二維陣列和一個整數,判斷陣列中是否含有該整數,
示例:
現有矩陣 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
給定 target = 5,回傳 true,
給定 target = 20,回傳 false,
限制:
0 <= n <= 1000
0 <= m <= 1000
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof
著作權歸領扣網路所有,商業轉載請聯系官方授權,非商業轉載請注明出處,
題解
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0) {
return false;
}
int m = matrix.length, n = matrix[0].length;
int row = 0, col = n - 1;
while(row < m && col >= 0) {
if(matrix[row][col] > target) {
col--;
}else if(matrix[row][col] < target) {
row++;
}else {
return true;
}
}
return false;
}
}
0ms 45.5MB
先求邊界,然后求值,如果比target小就row++,反之則col–,若有相等則回傳true,越界就是沒有相等,回傳false
更多題解點擊此處
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/11687.html
標籤:其他
