赞
踩
给你一个满足下述两条属性的 m x n 整数矩阵:
给你一个整数 target ,如果 target 在矩阵中,返回 true ;否则,返回 false 。
中等
示例 1:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
输出:true
示例 2:
输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
输出:false
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
解法1:先对每列第一个元素二分,再二分查找符合条件的某一行。时间复杂度
O
(
l
o
g
m
+
l
o
g
n
)
O(logm+logn)
O(logm+logn)
解法2:类似BST,从右上角开始查找,写法较简单,时间复杂度
O
(
l
o
g
(
m
∗
n
)
)
O(log(m∗n))
O(log(m∗n))
解2:
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row = matrix.size();
int col = matrix[0].size();
for (int i = 0, j = col - 1; i < row && j >= 0;
matrix[i][j] > target ? j-- : i++) {
if (matrix[i][j] == target)
return true;
}
return false;
}
};
解1:
class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int rowl = 0; int rowr = matrix.size() - 1; int rowmid = (rowl + rowr) / 2; while (rowl <= rowr) { rowmid = (rowl + rowr) / 2; if (matrix[rowmid][0] == target) return true; if (matrix[rowmid][0] > target) { rowr -= 1; } else if (matrix[rowmid][0] < target) { rowl += 1; } } int l = 0; int r = matrix[0].size() - 1; int m = (l + r) / 2; int row; if (rowl > rowr) row = rowr; else row = rowl; if (row < 0 || row >= matrix.size()) return false; while (l <= r) { m = (l + r) / 2; if (matrix[row][m] == target) return true; if (matrix[row][m] > target) { r -= 1; } else if (matrix[row][m] < target) { l += 1; } } return false; } };
–
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。