[哩扣] 4. Median of Two Sorted Arrays

楼主: cities516 (安安路过)   2024-12-26 00:16:40
4. Median of Two Sorted Arrays
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the
median of the two sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
暴力解当然是merge完再sort
但是这种小学生(习近平)都看得懂的解法应该对方看到会直接软掉
我看到两个解法
一个是two pointer 另一个是binary search
很不幸我已经老到看不懂binary search在干啥了
只讲两个指针
大家注意看啊 原本两个array就是帮你排序好的啊
所以解法就变得很简单啊 两个指针只在两个array上啊
然后哪个值比较小就递进哪个
然后递进到刚好两个arrays长度加起来的一半
就可以回传了
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
n = len(nums1)
m = len(nums2)
i = 0
j = 0
m1 = 0
m2 = 0
# Find median.
for count in range(0, (n + m) // 2 + 1):
m2 = m1
if i < n and j < m:
if nums1[i] > nums2[j]:
m1 = nums2[j]
j += 1
else:
m1 = nums1[i]
i += 1
elif i < n:
m1 = nums1[i]
i += 1
else:
m1 = nums2[j]
j += 1
# Check if the sum of n and m is odd.
if (n + m) % 2 == 1:
return float(m1)
else:
ans = float(m1) + float(m2)
return ans / 2.0
作者: KazamaSuisei (星风最强)   2024-12-26 00:19:00
别卷了...
作者: Rushia (みけねこ的鼻屎)   2024-12-26 00:21:00
别卷了
作者: PogChampLUL (火车站肥宅)   2024-12-26 00:36:00

Links booklink

Contact Us: admin [ a t ] ucptt.com