mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2025-12-06 05:24:07 +00:00
day 38: 74-search-a-2d-matrix
This commit is contained in:
parent
fbcb849210
commit
0706e1953c
11
74-search-a-2d-matrix/driver.cpp
Normal file
11
74-search-a-2d-matrix/driver.cpp
Normal 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;
|
||||
}
|
||||
62
74-search-a-2d-matrix/soln.cpp
Normal file
62
74-search-a-2d-matrix/soln.cpp
Normal 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;
|
||||
}
|
||||
8
74-search-a-2d-matrix/soln.hpp
Normal file
8
74-search-a-2d-matrix/soln.hpp
Normal 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);
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user