74 Search a 2D Matrix 搜索二維矩陣
Description:
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example:
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
題目描述:
編寫一個(gè)高效的算法來判斷 m x n 矩陣中,是否存在一個(gè)目標(biāo)值繁扎。該矩陣具有如下特性:
每行中的整數(shù)從左到右按升序排列廷雅。
每行的第一個(gè)整數(shù)大于前一行的最后一個(gè)整數(shù)括堤。
示例 :
示例 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
思路:
可以將二維矩陣看作一行數(shù)組
元素用 [index / matrix[0].size()][index % matrix[0].size()]定位
用二分查找即可
時(shí)間復(fù)雜度O(lg(mn)), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
if (matrix.empty() or matrix[0].empty()) return false;
int left = 0, right = matrix.size() * matrix[0].size() - 1, n = matrix[0].size();
while (left <= right)
{
int mid = left + ((right - left) >> 1);
int cur = matrix[mid / n][mid % n];
if (target == cur) return true;
else if (target > cur) left = mid + 1;
else right = mid - 1;
}
return false;
}
};
Java:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0 || matrix[0].length == 0) return false;
int left = 0, right = matrix.length * matrix[0].length - 1, n = matrix[0].length;
while (left <= right) {
int mid = left + ((right - left) >> 1);
int cur = matrix[mid / n][mid % n];
if (target == cur) return true;
else if (target > cur) left = mid + 1;
else right = mid - 1;
}
return false;
}
}
Python:
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
return target in set(chain(*matrix))