1
+ /**
2
+ * @param {number[] } nums1
3
+ * @param {number[] } nums2
4
+ * @return {number } 012345
5
+ */
6
+ var findMedianSortedArrays = function ( nums1 , nums2 ) {
7
+ if ( nums1 . length == 0 || nums2 . length == 0 ) {
8
+ if ( ( nums1 . length + nums2 . length ) % 2 == 1 ) {
9
+ const index = parseInt ( ( nums1 . length + nums2 . length ) / 2 )
10
+ return nums2 . length == 0 ? nums1 [ index ] : nums2 [ index ]
11
+ } else {
12
+ let nums = nums2 . length == 0 ? nums1 : nums2
13
+ const index = nums . length / 2
14
+ return ( nums [ index - 1 ] + nums [ index ] ) / 2
15
+ }
16
+ }
17
+
18
+ if ( nums1 . length > nums2 . length ) {
19
+ swap ( nums1 , nums2 )
20
+ }
21
+ const M = nums1 . length , N = nums2 . length
22
+ let min = 0 , max = M , half = parseInt ( ( M + N + 1 ) / 2 ) // 连个数组合并的中间值
23
+ while ( min <= max ) {
24
+ let i = parseInt ( ( min + max ) / 2 ) // nums1 的索引值
25
+ let j = half - i // num2 的索引值
26
+ if ( i < max && nums2 [ j - 1 ] > nums1 [ i ] ) {
27
+ min ++
28
+ } else if ( i > min && nums1 [ i - 1 ] > nums2 [ j ] ) {
29
+ max --
30
+ } else {
31
+ let maxLeft = 0
32
+ if ( i == 0 ) {
33
+ maxLeft = nums2 [ j - 1 ]
34
+ } else if ( j == 0 ) {
35
+ maxLeft = nums1 [ i - 1 ]
36
+ } else {
37
+ maxLeft = Math . max ( nums1 [ i - 1 ] , nums2 [ j - 1 ] )
38
+ }
39
+ if ( ( M + N ) % 2 == 1 ) {
40
+ return maxLeft
41
+ }
42
+ let minRight = 0
43
+ if ( i == M ) {
44
+ minRight = nums2 [ j ]
45
+ } else if ( j == N ) {
46
+ minRight = nums1 [ i ]
47
+ } else {
48
+ minRight = Math . min ( nums1 [ i ] , nums2 [ j ] )
49
+ }
50
+ return ( maxLeft + minRight ) / 2
51
+ }
52
+ }
53
+ return 0
54
+ } ;
55
+
56
+ function swap ( a , b ) {
57
+ let tmp = a
58
+ a = b
59
+ b = tmp
60
+ }
61
+
62
+ const nums1 = [ 4 , 5 ]
63
+ const nums2 = [ 1 , 2 , 3 ]
64
+ findMedianSortedArrays ( nums1 , nums2 )
65
+
66
+ /**
67
+ * 实现思路
68
+ * 先排除空数组的情况
69
+ * 数组从小到大排序
70
+ * 取小数组的中间值
71
+ * 取大数组的索引 = 总中间值-小数组中间值
72
+ * 循环直到符合条件
73
+ * 如果都不符合条件,那么说明中间值在两个数组的左边或者右边
74
+ */
0 commit comments