runtime 0 ms, beats 100% of cpp submissions
O(log(mn)) solution with explanation

tags: binary search

Search a 2D Matrix

๐Ÿ“– description

็ตฆๅฎšไธ€ๅ€‹่ขซๆŽ’ๅบ้Ž็š„ 2 ็ถญ้™ฃๅˆ—๏ผŒๆ‰พๅˆฐ็›ฎๆจ™ๅ…ƒ็ด ใ€‚

ex.
    Input: 
        matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3

    Output: true

๐Ÿง  solution

ๆœฌ้กŒๅฐฑๆ˜ฏไธ€ๅ€‹ binary search ็š„่ฎŠๅฝข๏ผŒ่ˆ‡ไธ€่ˆฌๆ–นๆณ•ไธๅŒ็š„ๅชๆœ‰ๅœจๆœๅฐ‹ๆ™‚้œ€่ฆๅฐ‡็ดขๅผ•ๅ€ผ่ฝ‰ๆ›ๆˆๅ…ฉๅ€‹ๅผ•ๆ•ธใ€‚

โณ time complexity

ๅ…ฑๆœ‰ mn ๅ€‹ๅ…ƒ็ด ๏ผŒ binary search ็š„ๆ™‚้–“่ค‡้›œๅบฆ็‚บ O(log(mn))
็ธฝๆ™‚้–“่ค‡้›œๅบฆ O(log(mn))

๐Ÿ“ code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
bool searchMatrix(vector<vector<int>>& mat, int t) {
int m = mat.size();
int n = mat[0].size();
int siz = m*n;
int l = 0,r = siz-1;
while(r>=l){
int mid = (r+l)/2;
if(mat[mid/n][mid%n] == t){ // ่ฝ‰ๆ›ๆˆๅ…ฉๅ€‹ๅบงๆจ™
return true;
}
else if(mat[mid/n][mid%n] < t){
l = mid+1;
}
else{
r = mid-1;
}
}
return false;
}
};