240 Search a 2D Matrix II 搜索二維矩陣 II
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 in ascending from left to right.
Integers in each column are sorted in ascending from top to bottom.
Example:
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
題目描述:
編寫(xiě)一個(gè)高效的算法來(lái)搜索 m x n 矩陣 matrix 中的一個(gè)目標(biāo)值 target考杉。該矩陣具有以下特性:
每行的元素從左到右升序排列铛漓。
每列的元素從上到下升序排列尖淘。
示例 :
現(xiàn)有矩陣 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
給定 target = 5竞端,返回 true赴背。
給定 target = 20赋兵,返回 false至扰。
思路:
- 展開(kāi)成一維數(shù)組, 用二分法查找
時(shí)間復(fù)雜度O(lgmn), 空間復(fù)雜度O(mn) - 每一行使用二分查找
時(shí)間復(fù)雜度O(mlgn), 空間復(fù)雜度O(1) - 從左下角(或者右上角)開(kāi)始查找
如果大, 指針向上移動(dòng);
如果小, 指針向右移動(dòng);
如果相等, 輸出 true
最后找不到輸出 false
時(shí)間復(fù)雜度O(m + n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
int row = matrix.size() - 1, col = 0;
while (row > -1 and col < matrix[0].size())
{
if (matrix[row][col] < target) ++col;
else if (matrix[row][col] > target) --row;
else if (matrix[row][col] == target) return true;
}
return false;
}
};
Java:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length - 1, col = 0;
while (row >= 0 && col < matrix[0].length) {
if (matrix[row][col] > target) row--;
else if (matrix[row][col] < target) col++;
else if (matrix[row][col] == target) return true;
}
return false;
}
}
Python:
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
return target in itertools.chain.from_iterable(matrix)