查詢兩個數組的中位數
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)).
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
思路
- 給定nums1給nums2,則中位數的位置一定能確定,len(nums1) + len(nums2) / 2的取整值,記爲median_idx
- 需要區分是len(nums1) + len(nums2)是奇數還是偶數
- 兩個指針,只需要從nums1和nums2頭部開始往後移動,將兩者中較小值放入新的數組
- 當新的數組的長度達到了median_idx,即可求中位數
- 過程中需要注意兩個數組長度不等的情況,防止下標越界
代碼
class Solution(object):
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: float
"""
median_idx = int((len(nums1) + len(nums2)) / 2)
index1, index2 = 0, len(nums1)
combine_list = nums1 + nums2
new_list = []
i = 0
while i <= median_idx:
if index1 < len(nums1) and index2 - len(nums1) < len(nums2):
new_list.append(min(combine_list[index1], combine_list[index2]))
if combine_list[index1] < combine_list[index2]:
index1 += 1
else:
index2 += 1
elif index1 >= len(nums1):
# nums1 is out of range, append nums2
new_list.append(combine_list[index2])
index2 += 1
elif index2 >= len(nums2):
# nums2 is out of range, append nums1
new_list.append(combine_list[index1])
index1 += 1
i += 1
if (len(nums1) + len(nums2)) % 2 == 0:
median = float(new_list[median_idx] + new_list[median_idx - 1]) / 2
else:
median = new_list[median_idx]
return median
本題以及其它leetcode題目代碼github地址: github地址