Skip to content

Commit 6e693ac

Browse files
committed
Search a 2D Matrix
1 parent 977d5be commit 6e693ac

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
### Matrix
4545

4646
- [Spirally traversing a matrix](https://practice.geeksforgeeks.org/problems/spirally-traversing-a-matrix-1587115621/1# "view question") - [Cpp Solution](./solutions/Spirally%20traversing%20a%20matrix.cpp)
47+
- [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/ "view question") - [Cpp Solution](./solutions/Search%20a%202D%20Matrix.cpp)
4748
- []( "view question") - [Cpp Solution](./solutions/.cpp)
4849

4950
### Strings
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Search a 2D Matrix
3+
==================
4+
5+
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
6+
7+
Integers in each row are sorted from left to right.
8+
The first integer of each row is greater than the last integer of the previous row.
9+
10+
Example 1:
11+
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
12+
Output: true
13+
14+
Example 2:
15+
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
16+
Output: false
17+
18+
Constraints:
19+
m == matrix.length
20+
n == matrix[i].length
21+
1 <= m, n <= 100
22+
-104 <= matrix[i][j], target <= 104
23+
*/
24+
25+
class Solution
26+
{
27+
public:
28+
bool searchMatrix(vector<vector<int>> &matrix, int target)
29+
{
30+
int n = matrix.size(), m = matrix[0].size();
31+
int r = 0, c = m - 1;
32+
33+
while (r < n && c >= 0)
34+
{
35+
if (matrix[r][c] == target)
36+
return true;
37+
else if (matrix[r][c] < target)
38+
r++;
39+
else
40+
c--;
41+
}
42+
return false;
43+
}
44+
};

0 commit comments

Comments
 (0)