Skip to content

Commit

Permalink
Update search_a_2d_matrix.cpp
Browse files Browse the repository at this point in the history
Hello there, I`d like to propose my own solution for this binary search problem as it reduces the problem to "704. Binary Search" problem.
Reduction is performed by considering matrix as whole 1D array of length m*n, elements in this "array" are stored in sorted order as well: access to the position inside a matrix can be done by 2 simple computations:
```Array[k] == Matrix[k / n][k % n]```,
where n is the number of columns in a matrix (We simply linearize our matrix)
  • Loading branch information
Abusagit authored Oct 15, 2022
1 parent fd465a1 commit 32e2ea6
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions cpp/neetcode_150/05_binary_search/search_a_2d_matrix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,41 @@ class Solution {
return false;
}
};

// Same approach with implicit array linearization
// T(n) = O(log_2(mn)) = O(log_2(m) + log_2(n))
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {

int left = 0;
int m = matrix.size();
int n = matrix[0].size();
int right = m * n - 1;

while (left <= right){

int middle = right + (left - right) / 2;

// compute sub-indices using matrix structure
int row = middle / n;
int col = middle % n;


//ordinary binary search
int middle_x = matrix[row][col];
if (target > middle_x){
left = ++middle;
} else if (target < middle_x){
right = --middle;
} else {
return true;
}


}

return false;

}
};

0 comments on commit 32e2ea6

Please sign in to comment.