二分查找
python
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int):
m = len(matrix)
n = len(matrix[0])
for line in matrix:
if target < line[0] or target > line[-1]:
continue
else:
left, right = 0, n-1
while left <= right:
mid = int((left + (right-left)/2))
if line[mid] == target:
return True
elif line[mid] < target:
left = mid + 1
elif line[mid] > target:
right = mid - 1
return False
c++
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
// 先定位到某行,就可以砍掉一半元素,再在该行中二分查找
int row = matrix.size(), column = matrix[0].size();
int up = 0, down = row - 1;
int left = 0, right = column - 1;
// 定位到某行
while (up <= down) {
int mid = up + (down - up) / 2;
if (matrix[mid][0] == target) {
return true;
} else if (matrix[mid][0] > target) {
down = mid - 1;
} else if (matrix[mid][0] < target) {
up = mid + 1;
}
}
// 边界溢出判断
if (up > row || down < 0) return false;
// 此时up为第一列元素中大于target的最小元素的行索引
while (left <= right) {
int mid = left + (right - left) / 2;
if (matrix[up-1][mid] == target) {
return true;
} else if (matrix[up-1][mid] > target) {
right = mid - 1;
} else if (matrix[up-1][mid] < target) {
left = mid + 1;
}
}
return false;
}
};