LeetCode problem No.4.
No.3 is here.
4. Median of Two Sorted Arrays
https://leetcode.com/problems/median-of-two-sorted-arrays/
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example
nums1 = [1, 3] nums2 = [2] The median is 2.0
Code
object Solution { def findMedianSortedArrays(nums1: Array[Int], nums2: Array[Int]): Double = { val totalSize = nums1.length + nums2.length val index:Int = totalSize/2 val connected = (nums1 ++ nums2).sorted if(totalSize % 2 == 0) (connected(index) + connected(index-1))/2.0 else connected(index) } }
Methods
- Calculate median
index
fromm
andn
. - Make union array from
nums1
andnums2
, and sort it. - If
m
+n
is odd,index
number of union array is median. - If
m
+n
is even, average ofindex
andindex-1
numbers of union array is median.
Results
Runtime: 452 ms, faster than 76.98% of Scala online submissions for Median of Two Sorted Arrays. Memory Usage: 59.2 MB, less than 94.59% of Scala online submissions for Median of Two Sorted Arrays.
Code 2
object Solution { def findMedianSortedArrays(nums1: Array[Int], nums2: Array[Int]): Double = { val total = nums1.length + nums2.length val index = total/2 var pre = 0 var target = 0 var index1 = -1 var index2 = -1 for { i <- 0 to targetIndex } { val (next1, next2) = if(index1 == nums1.length-1) (index1, index2+1) else if(index2 == nums2.length-1) (index1+1, index2) else if(nums1(index1+1) > nums2(index2+1)) (index1, index2+1) else (index1+1, index2) if(i == index - 1) pre = if(index1 == next1) nums2(next2) else nums1(next1) if(i == index) target = if(index1 == next1) nums2(next2) else nums1(next1) index1 = next1 index2 = next2 } if(total % 2 == 0) (pre + target)/2.0 else target } }
Methods
- Calculate median
index
fromm
andn
. - Loop 0 to
index
- If
m
+n
is odd,target
is median. - If
m
+n
is even, average ofpre
andtarget
is median.
Results
Runtime: 432 ms, faster than 90.48% of Scala online submissions for Median of Two Sorted Arrays. Memory Usage: 59.8 MB, less than 91.89% of Scala online submissions for Median of Two Sorted Arrays.