4. Looking for a median of two ordered arrays
Topic links: https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
Title Description
Given two ordered arrays of size n, and m nums1
and nums2
.
Please find both the median and orderly array, and requires time complexity of the algorithm is O(log(m + n))
.
You can assume nums1
and nums2
will not be both empty.
Examples
Example. 1:
nums1 = [. 1,. 3]
nums2 = [2]
, the median is 2.0
Example 2:
nums1 = [. 1, 2]
nums2 = [3,. 4]
, the median is (2 + 3) / 2 = 2.5
Code
Note: The following is what I wrote, seems wrong, I forgot to forget how time complexity, the time should be in charge of the point of view is wrong
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
nums = nums1 + nums2
n = len(nums)
for i in range(n):
temp = nums[i]
for j in range(i,n):
if temp > nums[j]:
nums[i] = nums[j]
nums[j] = temp
temp = nums[i]
if n % 2 == 0:
return (nums[n//2 - 1]+nums[n//2])/2
return nums[(n-1)//2]
Note: The following is not my writing, Baidu refer others.
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
m, n = len(nums1), len(nums2)
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
if n == 0:
raise ValueError
imin, imax, half_len = 0, m, (m + n + 1) / 2
while imin <= imax:
i = int((imin + imax) / 2)
j = int(half_len - i)
if i < m and nums2[j-1] > nums1[i]:
imin = i + 1
elif i > 0 and nums1[i-1] >nums2[j]:
imax = i - 1
else:
if i == 0: max_of_left = nums2[j-1]
elif j == 0: max_of_left = nums1[i-1]
else: max_of_left = max(nums1[i-1], nums2[j-1])
if (m + n) % 2 == 1:
return max_of_left
if i == m: min_of_right = nums2[j]
elif j == n: min_of_right = nums1[i]
else: min_of_right = min(nums1[i], nums2[j])
return (max_of_left + min_of_right) / 2.0
# 作者:jutraman
# 链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/pythonliang-ge-you-xu-shu-zu-de-zhong-wei-shu-by-j/
# 来源:力扣(LeetCode)
# c著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。