Skip to content

Commit 1ab6297

Browse files
committed
feat: add Search a 2D Matrix
1 parent 31e8af9 commit 1ab6297

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,4 @@ https://neetcode.io/roadmap
2828
| 853 | [Car Fleet](https://leetcode.com/problems/car-fleet/) | Medium | [TypeScript](./TypeScript/853.car-fleet.ts) | Stack |
2929
| 84 | [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/) | Hard | [TypeScript](./TypeScript/84.largest-rectangle-in-histogram.ts) | Stack |
3030
| 704 | [Binary Search](https://leetcode.com/problems/binary-search/) | Easy | [TypeScript](./TypeScript/704.binary-search.ts) | Binary Search |
31+
| 74 | [Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | Medium | [TypeScript](./TypeScript/74.search-a-2d-matrix.ts) | Binary Search |

TypeScript/74.search-a-2d-matrix.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
function searchMatrix(matrix: number[][], target: number): boolean {
2+
let low, high, mid;
3+
let targetRow = null;
4+
5+
low = 0;
6+
high = matrix.length - 1;
7+
while (low <= high) {
8+
mid = low + Math.floor((high - low) / 2);
9+
10+
if (
11+
matrix[mid][0] <= target &&
12+
target <= matrix[mid][matrix[mid].length - 1]
13+
) {
14+
targetRow = mid;
15+
break;
16+
} else if (matrix[mid][0] > target) {
17+
high = mid - 1;
18+
} else {
19+
low = mid + 1;
20+
}
21+
}
22+
if (targetRow === null) return false;
23+
24+
low = 0;
25+
high = matrix[targetRow].length - 1;
26+
while (low <= high) {
27+
mid = low + Math.floor((high - low) / 2);
28+
29+
if (matrix[targetRow][mid] === target) {
30+
return true;
31+
} else if (matrix[targetRow][mid] > target) {
32+
high = mid - 1;
33+
} else {
34+
low = mid + 1;
35+
}
36+
}
37+
38+
return false;
39+
}

0 commit comments

Comments
 (0)