File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * find the mid index
3+ * if the length is even, find the mid two numbers, midIndex and midIndex - 1 (index starts from 0)
4+ */
5+ function findMedianSortedArrays ( nums1 : number [ ] , nums2 : number [ ] ) : number {
6+ const l1 = nums1 . length ;
7+ const l2 = nums2 . length ;
8+ const l = l1 + l2 ;
9+
10+ let i1 = - 1 ;
11+ let i2 = - 1 ;
12+ let lastArray : 1 | 2 = 1 ;
13+
14+ const isOdd = l % 2 === 1 ;
15+ const midIndex = l / 2 ;
16+
17+ for ( let j = 0 ; j < midIndex ; j ++ ) {
18+ switch ( true ) {
19+ case i1 === l1 - 1 :
20+ i2 ++ ;
21+ lastArray = 2 ;
22+ break ;
23+ case i2 === l2 - 1 :
24+ i1 ++ ;
25+ lastArray = 1 ;
26+ break ;
27+ case nums1 [ i1 + 1 ] < nums2 [ i2 + 1 ] :
28+ i1 ++ ;
29+ lastArray = 1 ;
30+ break ;
31+ case nums1 [ i1 + 1 ] >= nums2 [ i2 + 1 ] :
32+ i2 ++ ;
33+ lastArray = 2 ;
34+ break ;
35+ default :
36+ break ;
37+ }
38+ }
39+
40+ if ( isOdd ) {
41+ return lastArray === 1 ? nums1 [ i1 ] : nums2 [ i2 ] ;
42+ }
43+
44+ const mid1 = lastArray === 1 ? nums1 [ i1 ] : nums2 [ i2 ] ;
45+
46+ /* find the next mid number */
47+ let mid2 : number ;
48+ if ( i1 === l1 - 1 ) {
49+ mid2 = nums2 [ i2 + 1 ] ;
50+ } else if ( i2 === l2 - 1 ) {
51+ mid2 = nums1 [ i1 + 1 ] ;
52+ } else {
53+ mid2 = Math . min ( nums1 [ i1 + 1 ] , nums2 [ i2 + 1 ] ) ;
54+ }
55+
56+ console . log ( { mid1, mid2 } ) ;
57+
58+ return ( mid1 + mid2 ) / 2 ;
59+ }
You can’t perform that action at this time.
0 commit comments