題目描述
編寫一個高效的算法來判斷 m x n 矩陣中,是否存在一個目標值。該矩陣具有如下特性:
每行中的整數從左到右按升序排列。
每行的第一個整數大於前一行的最後一個整數。
示例 1:
輸入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
輸出: true
示例 2:
輸入:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
輸出: false
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/search-a-2d-matrix
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
代碼實現
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length ==0)
return false;
int lowIndex =0,highIndex=0;//可能的位置,target在這兩行之間,包含這兩行
for(int n=0;n<matrix.length;n++){
if(matrix[n][0]<target){
lowIndex = n;
continue;
}else if(matrix[n][0] == target){
return true ;
}else{
highIndex = n;
break;
}
}
highIndex=(highIndex == 0)?lowIndex:highIndex;
//把範圍縮短的儘可能短的行之間
for (int j = 0; j < matrix[lowIndex].length; j++) {
if(matrix[lowIndex][j] == target)
return true;
}
return false;
}
}