File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ // This is a O((m+n)/2) solution. It's a bit trickier to code the O(m+n) version.
2
+
3
+ function findMedianSortedArrays ( nums1 : number [ ] , nums2 : number [ ] ) : number {
4
+ const totalLength = nums1 . length + nums2 . length ;
5
+ const halfLength = Math . floor ( totalLength / 2 ) ;
6
+ // Handle even and odd lengths to indexes: 20 -> 9, 10; 21 -> 10, 10
7
+ const [ targetIndex1 , targetIndex2 ] = [
8
+ totalLength % 2 === 0 ? halfLength - 1 : halfLength ,
9
+ halfLength ,
10
+ ] ;
11
+
12
+ const arr : number [ ] = [ ] ;
13
+ let p1 = 0 ,
14
+ p2 = 0 ,
15
+ n1 = 0 ,
16
+ n2 = 0 ;
17
+ while ( p1 < nums1 . length && p2 < nums2 . length ) {
18
+ n1 = nums1 [ p1 ] ;
19
+ n2 = nums2 [ p2 ] ;
20
+ if ( n1 <= n2 ) {
21
+ arr . push ( n1 ) ;
22
+ p1 += 1 ;
23
+ } else {
24
+ arr . push ( n2 ) ;
25
+ p2 += 1 ;
26
+ }
27
+
28
+ if ( arr . length > targetIndex2 ) {
29
+ return ( arr [ targetIndex1 ] + arr [ targetIndex2 ] ) / 2 ;
30
+ }
31
+ }
32
+
33
+ if ( p1 === nums1 . length ) {
34
+ arr . push ( ...nums2 . slice ( p2 ) ) ;
35
+ } else if ( p2 === nums2 . length ) {
36
+ arr . push ( ...nums1 . slice ( p1 ) ) ;
37
+ }
38
+ return ( arr [ targetIndex1 ] + arr [ targetIndex2 ] ) / 2 ;
39
+ }
You can’t perform that action at this time.
0 commit comments