-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch in a 2D matrix.cpp
95 lines (82 loc) · 1.87 KB
/
Search in a 2D matrix.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Problem Statement Link - https://leetcode.com/problems/search-a-2d-matrix/
// Brute Force
// Time : O(m*n); Space: O(1)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0 && target == 0)
{
return false;
}
int m= matrix.size();
int n= matrix[0].size();
for(int i=0; i<m; i++)
{
for(int j=0;j<n; j++)
{
if(matrix[i][j] == target)
{
return true;
}
}
}
return false;
}
};
// Row-Column remove
// Time : O(m + n); Space : O(1)
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if(matrix.size() == 0 && target == 0)
{
return false;
}
int smallest = matrix[0][0], largest = matrix[matrix.size() - 1][matrix.size() - 1];
if (target < smallest || target > largest)
return false;
int m = matrix.size();
int n = matrix[0].size();
int row = 0,col = n-1;
while(row < m and col >= 0)
{
if(matrix[row][col] == target)
return true;
else if(matrix[row][col] < target)
{
row++;
}
else
{
col--;
}
}
return false;
}
};
// Binary Search
// Time: O(log(m*n)); Space: O(log(m) + log(n))
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int n = matrix.size();
int m = matrix[0].size();
int l = 0, r = m * n - 1;
while (l < r)
{
mid = (l + r - 1) / 2;
if (matrix[mid / m][mid % m] < target)
{
l = mid + 1;
}
else
{
r = mid;
}
}
if( matrix[r / m][r % m] == target ) // An array can be converted into n * m matrix: a[x] → matrix[x / m][x % m]
return true;
else
return false;
}
};