File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
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 ;
You can’t perform that action at this time.
0 commit comments