forked from strang3-r/Leetcode75
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarySearch.cpp
35 lines (31 loc) · 909 Bytes
/
binarySearch.cpp
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
class Solution
{
public:
bool searchMatrix(vector<vector<int>> &matrix, int target)
{
// nrows---> Number of rows, mcols---> Number of columns
int nrows = matrix.size();
int mcols = matrix[0].size(); // Because, No. of columns = length of any particular row
int start = 0;
int end = nrows * mcols - 1;
int mid = (start + end) / 2; // Finding mid index
while (start <= end)
{
mid = (start + end) / 2;
int element = matrix[mid / mcols][mid % mcols]; // Finding the element at mid index
if (element == target)
{
return true;
}
else if (element < target)
{
start = mid + 1;
}
else //(element > target)
{
end = mid - 1;
}
}
return 0;
}
};