File tree 2 files changed +53
-0
lines changed
src/search-a-2d-matrix-ii
2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -28,6 +28,7 @@ Progress: 20/
28
28
| 196| [ Delete Duplicate Emails] ( https://leetcode.com/problems/delete-duplicate-emails/ ) | [ SQL] ( ./src/delete-duplicate-emails/res.txt ) | Easy|
29
29
| 197| [ Rising Temperature] ( https://leetcode.com/problems/rising-temperature/ ) | [ SQL] ( ./src/rising-temperature/res.txt ) | Easy|
30
30
| 206| [ Reverse Linked List] ( https://leetcode.com/problems/reverse-linked-list/ ) | [ JavaScript] ( ./src/reverse-linked-list/res.js ) | Easy|
31
+ | 240| [ Search a 2D Matrix II] ( https://leetcode.com/problems/search-a-2d-matrix-ii/ ) | [ JavaScript] ( ./src/search-a-2d-matrix-ii/res.js ) | Medium|
31
32
| 342| [ Power of Four] ( https://leetcode.com/problems/power-of-four/ ) | [ JavaScript] ( ./src/power-of-four/res.js ) | Easy|
32
33
| 344| [ Reverse String] ( https://leetcode.com/problems/reverse-string/ ) | [ JavaScript] ( ./src/reverse-string/res.js ) | Easy|
33
34
| 404| [ Sum of Left Leaves] ( https://leetcode.com/problems/sum-of-left-leaves/ ) | [ JavaScript] ( ./src/sum-of-left-leaves/res.js ) | Easy|
Original file line number Diff line number Diff line change
1
+ // Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
2
+
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
+ // For example,
6
+
7
+ // Consider the following matrix:
8
+
9
+ // [
10
+ // [1, 4, 7, 11, 15],
11
+ // [2, 5, 8, 12, 19],
12
+ // [3, 6, 9, 16, 22],
13
+ // [10, 13, 14, 17, 24],
14
+ // [18, 21, 23, 26, 30]
15
+ // ]
16
+ // Given target = 5, return true.
17
+
18
+ // Given target = 20, return false.
19
+
20
+ /**
21
+ * res.js
22
+ * @authors Joe Jiang (hijiangtao@gmail.com)
23
+ * @date 2017-02-26 22:12:39
24
+ * @version $Id$
25
+ *
26
+ *
27
+ * @param {number[][] } matrix
28
+ * @param {number } target
29
+ * @return {boolean }
30
+ */
31
+ let searchMatrix = function ( matrix , target ) {
32
+ // Nothing in the matrix
33
+ if ( matrix . length === 0 || matrix [ 0 ] === 0 ) {
34
+ return false ;
35
+ }
36
+
37
+ let rowlen = matrix . length ,
38
+ collen = matrix [ 0 ] . length ;
39
+
40
+ let i = 0 , j = collen - 1 ;
41
+ while ( i >= 0 && i < rowlen && j >= 0 && j < collen ) {
42
+ if ( matrix [ i ] [ j ] === target ) {
43
+ return true ;
44
+ } else if ( matrix [ i ] [ j ] > target ) {
45
+ j -= 1 ;
46
+ } else {
47
+ i += 1 ;
48
+ }
49
+ }
50
+
51
+ return false ;
52
+ } ;
You can’t perform that action at this time.
0 commit comments