day 38: 74-search-a-2d-matrix

This commit is contained in:
Kaushik Narayan R 2023-11-13 13:39:41 -07:00
parent fbcb849210
commit 0706e1953c
3 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,11 @@
#include "soln.hpp"
int main()
{
vector<vector<int>> matrix = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
int target = 3;
bool answer = true;
Solution soln;
cout << "Searched matrix correctly? " << soln.test(matrix, target, answer) << endl;
return 0;
}

View File

@ -0,0 +1,62 @@
#include "soln.hpp"
bool Solution::searchMatrix(vector<vector<int>> &matrix, int target)
{
int m = matrix.size(), n = matrix[0].size();
if (m == 1 && n == 1)
{
return matrix[0][0] == target;
}
int low = 0, high = m - 1;
int row_mid = (low + high) / 2, mid = -1;
if (m != 1)
{
while (low < high)
{
if (matrix[row_mid][0] == target)
{
return true;
}
else
{
if (matrix[row_mid][0] > target)
{
high = row_mid;
}
else if (matrix[row_mid][n - 1] < target)
{
low = row_mid + 1;
}
else
{
break;
}
}
row_mid = (low + high) / 2;
}
}
low = 0, high = n - 1;
mid = (low + high) / 2;
while (low < high)
{
if (matrix[row_mid][mid] == target)
{
return true;
}
else if (matrix[row_mid][mid] < target)
{
low = mid + 1;
}
else
{
high = mid;
}
mid = (low + high) / 2;
}
return matrix[row_mid][mid] == target;
}
bool Solution::test(vector<vector<int>> &matrix, int target, bool answer)
{
return searchMatrix(matrix, target) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
bool searchMatrix(vector<vector<int>> &matrix, int target);
bool test(vector<vector<int>> &matrix, int target, bool answer);
};