前言
刷了那麼多題,昨天竟然被問住了!!恥辱啊!!!!今天起刷題flag復活!!!!
題目描述
給定M×N矩陣,每一行、每一列都按升序排列,請編寫代碼找出某元素。
示例:
現有矩陣 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。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/sorted-matrix-search-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題思路
- 從右上角開始找,如果當前值大於目標值,則往左找,j–,如果當前值小於目標值,則往下找,i++, 如果相等,返回。
- 循環結束條件是i > 行數-1,或j < 0
代碼
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 ) return false;
int i = 0, j = matrix[0].length - 1;
if(j == -1) return false;
while(i <= matrix.length - 1 && j >= 0){
if(matrix[i][j] > target){
j--;
} else if(matrix[i][j] < target){
i++;
} else {
return true;
}
}
return false;
}
}