class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
}
};
74. 搜索二维矩阵
编写一个高效的算法来判断 m x n
矩阵中,是否存在一个目标值。该矩阵具有如下特性:
示例 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
相似题目
原站题解
python3 解法, 执行用时: 44 ms, 内存消耗: 15.3 MB, 提交时间: 2022-08-17 10:23:10
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: from functools import reduce return target in reduce(lambda x, y: x+y, matrix)
golang 解法, 执行用时: 0 ms, 内存消耗: 2.5 MB, 提交时间: 2022-08-17 10:18:00
func searchMatrix(matrix [][]int, target int) bool { m, n := len(matrix), len(matrix[0]) i := sort.Search(m*n, func(i int) bool { return matrix[i/n][i%n] >= target }) return i < m*n && matrix[i/n][i%n] == target }