Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 7632956

Browse files
Create Search-a-2D-Matrix-II.js (ignacio-chiazzo#14)
* Create Search-a-2D-Matrix-II.js * Update Search-a-2D-Matrix-II.js * Update Search-a-2D-Matrix-II.js * Update Search-a-2D-Matrix-II.js
1 parent a692e00 commit 7632956

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
https://leetcode.com/problems/search-a-2d-matrix-ii/description/
3+
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
4+
Integers in each row are sorted in ascending from left to right.
5+
Integers in each column are sorted in ascending from top to bottom.
6+
Example:
7+
Consider the following matrix:
8+
[
9+
[1, 4, 7, 11, 15],
10+
[2, 5, 8, 12, 19],
11+
[3, 6, 9, 16, 22],
12+
[10, 13, 14, 17, 24],
13+
[18, 21, 23, 26, 30]
14+
]
15+
Given target = 5, return true.
16+
Given target = 20, return false.
17+
*/
18+
19+
/**
20+
* @param {number[][]} matrix
21+
* @param {number} target
22+
* @return {boolean}
23+
*/
24+
var searchMatrix = function(matrix, target) {
25+
if (matrix.length == 0)
26+
return false
27+
var lastCol = matrix[0].length - 1;
28+
var firstRow = 0;
29+
30+
while(lastCol >= 0 && firstRow < matrix.length) {
31+
if(matrix[firstRow][lastCol] == target) {
32+
return true;
33+
} else if(matrix[firstRow][lastCol] > target) {
34+
lastCol--;
35+
} else {
36+
firstRow++;
37+
}
38+
}
39+
40+
return false;
41+
};
42+
43+
const matrix1 = [
44+
[1,4,7, 11,15],
45+
[2,5,8, 12,19],
46+
[3,6,9, 16,22],
47+
[10,13,14, 17,24],
48+
[18,21,23, 26,30]
49+
];
50+
51+
var main = function(n) {
52+
console.log(searchMatrix(matrix1, 5));
53+
console.log(searchMatrix(matrix1, 0));
54+
console.log(searchMatrix(matrix1, 15));
55+
}
56+
57+
module.exports.main = main;

0 commit comments

Comments
 (0)