LeetCode/solutions/74. Search a 2D Matrix.md
2019-02-21 19:40:18 +08:00

25 lines
877 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/)
# 思路
就是一个二分查找。将矩阵展开成一个很长的有序数组下标low从0开始下标high从`m*n - 1`开始然后二分查找中间下标mid对应的元素为`matrix[mid / n][mid % n]`。
时间复杂度O(log(mn))空间复杂度O(1)
# C++
``` C++
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.empty()) return false;
int m = matrix.size(), n = matrix[0].size();
int low = 0, high = m * n - 1;
while(low <= high){
int mid = (high - low) / 2 + low;
int tmp = matrix[mid / n][mid % n];
if(tmp == target) return true;
if(tmp < target) low = mid + 1;
else high = mid - 1;
}
return false;
}
};
```