File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
Problems/14-Search-a-2D-Matrix Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change
1
+ function searchMatrix ( matrix : number [ ] [ ] , target : number ) : boolean {
2
+ function searchMx ( matrix : number [ ] [ ] , target : number ) : number {
3
+ let left = 0 , right = matrix . length - 1 ;
4
+ while ( left <= right ) {
5
+ let mid = Math . floor ( ( left + right ) / 2 ) ;
6
+ let head = matrix [ mid ] [ 0 ] ;
7
+ let tail = matrix [ mid ] [ matrix [ mid ] . length - 1 ] ;
8
+ if ( target > tail ) left = mid + 1 ;
9
+ else if ( target < head ) right = mid - 1 ;
10
+ else if ( target <= tail && target >= head ) return mid ;
11
+ }
12
+ return - 1 ;
13
+ }
14
+
15
+ if ( searchMx ( matrix , target ) === - 1 ) return false ;
16
+ const arr = matrix [ searchMx ( matrix , target ) ] ;
17
+ let left = 0 ;
18
+ let right = arr . length - 1 ;
19
+ while ( left <= right ) {
20
+ let mid = Math . floor ( ( left + right ) / 2 ) ;
21
+ if ( arr [ mid ] > target ) right = mid - 1 ;
22
+ else if ( arr [ mid ] < target ) left = mid + 1 ;
23
+ else return true ;
24
+ }
25
+ return false ;
26
+ } ;
You can’t perform that action at this time.
0 commit comments