Skip to content

Commit 516047e

Browse files
committed
Day 65 leet code problem - Search a 2D matrix
1 parent 6a57714 commit 516047e

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -169,4 +169,4 @@ Include contains single header implementation of data structures and some algori
169169
| Problem | Solution |
170170
| :------------ | :----------: |
171171
| Given a sorted integer array without duplicates, return the summary of its ranges. For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].| [summary_ranges.cpp](leet_code_problems/summary_ranges.cpp)|
172-
172+
| Given a 2D matrix, with following properties <ul><li>Integers in each row are sorted in ascending from left to right.</li></ul><ul><li>Integers in each column are sorted in ascending from top to bottom.</ul></li>|[search2DII.cpp](leet_code_problems/search2DII.cpp)|

leet_code_problems/search2DII.cpp

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
3+
* Integers in each row are sorted in ascending from left to right.
4+
* Integers in each column are sorted in ascending from top to bottom.
5+
*/
6+
7+
#include <iostream>
8+
#include <vector>
9+
10+
bool searchMatrix( std::vector<std::vector<int>> matrix, int target ) {
11+
int M = matrix.size();
12+
int N = matrix[0].size();
13+
if ( target < matrix[0][0] || target > matrix[M-1][N-1] ) {
14+
return false;
15+
}
16+
17+
int row = 0;
18+
int col = N - 1;
19+
while ( row <= M -1 && col >= 0 ) {
20+
if ( matrix[row][col] == target ) {
21+
return true;
22+
} else if ( matrix[row][col] > target ) {
23+
col--;
24+
} else {
25+
row++;
26+
}
27+
}
28+
return false;
29+
}
30+
31+
int main() {
32+
std::vector<std::vector<int>> matrix = {
33+
{1, 4, 7, 11, 15},
34+
{2, 5, 8, 12, 19},
35+
{3, 6, 9, 16, 22},
36+
{10, 13, 14, 17, 24},
37+
{18, 21, 23, 26, 30}
38+
};
39+
std::cout << searchMatrix(matrix, 5) << std::endl;
40+
std::cout << searchMatrix(matrix, 20) << std::endl;
41+
return 0;
42+
}
43+

0 commit comments

Comments
 (0)