文章目录
题目
一题三解
直接搜索
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for (const auto& row: matrix) {
auto it = lower_bound(row.begin(), row.end(), target);
if (it != row.end() && *it == target) {
return true;
}
}
return false;
}
};
二分查找
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
for (const auto& row: matrix) {
auto it = lower_bound(row.begin(), row.end(), target);
if (it != row.end() && *it == target) {
return true;
}
}
return false;
}
};
*(重点)二叉搜索树
这种排序的二维数组结构,很明显总能找到一个角度来看,然后实现二叉搜索树的结构,这个就是从右上角看,它就是一个二叉搜索树。
class Solution {
public:
//从右上角看就是一棵二叉搜索树!
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size(),m = matrix[0].size();
int i = 0,j = m-1;
while(i<n&&j>=0){
if(matrix[i][j]==target)return true;
if(matrix[i][j]>target){
j--;
}else{
i++;
}
}
return false;
}
};
- 我想说golang yyds!
func searchMatrix(matrix [][]int, target int) bool {
m, n := len(matrix), len(matrix[0])
x, y := 0, n-1
for x < m && y >= 0 {
if matrix[x][y] == target {
return true
}
if matrix[x][y] > target {
y--
} else {
x++
}
}
return false
}