You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Traverse through the matrix and check for the target.
If the target is found, return true.
finally return false.
O(N*logM) Time and constant space solution
Search using binary search.
Code
classSolution{
boolbinarySearch(vector<int> &nums, int target){
int n = nums.size(), l = 0, r = n - 1;
while (l <= r){
int mid = l + (r - l) / 2;
if (nums[mid] == target)
returntrue;
elseif (target > nums[mid])
l = mid + 1;
else
r = mid - 1;
}
returnfalse;
}
public:boolsearchMatrix(vector<vector<int>> &matrix, int target){
int n = matrix.size(), m = matrix[0].size();
for (int i = 0; i < n; i++){
if (matrix[i][0] <= target && target <= matrix[i][m - 1])
returnbinarySearch(matrix[i], target);
}
returnfalse;
}
};
O(log(N*M)) Time and O(1) space
Complete Binary search on matrix.
mid/m : row , mid%m : column
Code
classSolution{
public:boolsearchMatrix(vector<vector<int>> &matrix, int target){
int n = matrix.size(), m = matrix[0].size();
int l = 0, h = (n * m) - 1;
while (l <= h){
int mid = l + (h - l) / 2;
if (matrix[mid / m][mid % m] == target)
returntrue;
elseif (matrix[mid / m][mid % m] < target)
l = mid + 1;
else
h = mid - 1;
}
returnfalse;
}
};