Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

search-a-2d-matrix-ii #485

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions C++/search-a-2d-matrix-ii.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
// Get the number of rows and columns in the matrix
int n = matrix.size();
int m = matrix[0].size();

// Start from the top-right corner of the matrix
int r = 0;
int c = m - 1;

// Loop until we reach either the bottom row or the leftmost column
while (r < n and c > -1) {
// If the current element is equal to the target, return true
if (matrix[r][c] == target) {
return true;
}
// If the current element is greater than the target, move left
else if (matrix[r][c] > target) {
c--;
}
// If the current element is less than the target, move down
else {
r++;
}
}

// If the target is not found, return false
return false;
}
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu
| 033 | [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/) | [Python](./Python/search-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium | | Binary Search |
| 153 | [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/) | [Python](./Python/find-minimum-in-rotated-sorted-array.py) | _O(logn)_ | _O(1)_ | Medium | | Binary Search |
| 704 | [Binary Search](https://leetcode.com/problems/binary-search/) | [C++](./C++/BinarySearch.cpp) | _O(logn)_ | _O(1)_ | Easy | | Binary Search |
| 240 | [Search a 2D Matrix II](https://leetcode.com/problems/search-a-2d-matrix-ii/) | [C++](./C++/SearchA2DMatrixII.cpp) | _O(m + n)_| _O(1)_ | Medium | | Binary Search |

<br/>
<div align="right">
Expand Down