forked from super30admin/Binary-Search-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem1.cpp
More file actions
36 lines (34 loc) · 810 Bytes
/
Copy pathproblem1.cpp
File metadata and controls
36 lines (34 loc) · 810 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Time Complexity : T(n) = O(logn)
// Space Complexity :S(n)=O(1)
// Did this code successfully run on Leetcode :yes
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
//base case
if(matrix.size()==0) return false;
int m=matrix.size();
int n=matrix[0].size();
int low=0;
int high=m*n-1;
while(low<=high)
{
int mid=low+(high-low)/2;
int c=mid%n;
int r=mid/n;
if(matrix[r][c]==target)
{
return true;
}
else if(matrix[r][c]>target)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
return false;
}
};