LeetCode 4. Median of Two Sorted Arrays Python3
Description
Click Title
There are TWO the sorted Arrays nums1 and nums2 of size and n-m 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 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
problem analysis
Just beginning to see this is a difficult question , but after reading the title and did not find the place so what do not understand, the topic means that given two ordered array, the two arrays to find the median, and the title example given to explain what is the median, so although the subject is difficult to label the title, but as long as the two ordered arrays are combined, then return to the median.Recent study Python, does not mean re-start it, because learned before C ++, Java, is in accordance with the mode of thinking of learning before had to try to achieve with Python, then go and see someone else written in Python simple, efficient code, so there If the time could not understand the code I wrote, but also look Wuguai, but I will look at yourself in the comments section of code, strive to improve their programming skills, are interested can exchange oh.
Code
The first method to achieve
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
length = len(nums1) + len(nums2)
flag = length % 2
res = []
j = 0
k = 0
while j < len(nums1) and k < len(nums2):
if nums1[j] < nums2[k]:
res.append(nums1[j])
j += 1
else:
res.append(nums2[k])
k += 1
while j < len(nums1):
res.append(nums1[j])
j += 1
while k < len(nums2):
res.append(nums2[k])
k += 1
result = 0.
if flag == 0:
result = (res[length // 2] + res[length // 2 - 1]) / 2.
else:
result = res[length // 2]
return result
The second method to achieve
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
length = len(nums1) + len(nums2)
res = []
while nums1 and nums2:
res.append(nums1.pop(0) if nums1[0] < nums2[0] else nums2.pop(0))
if nums1:
res += nums1
else:
res += nums2
if length % 2 == 0:
result = (res[length // 2 - 1] + res[length // 2]) / 2.
else:
result = res[length // 2] * 1.
return result
Comparing operating results
As can be seen from the figure, the use of encapsulated Python method than running or to write their own efficient, so learn to stand on the shoulders of giants, by an external was made not to repeat the wheel.
ok! I'm done, if you have other methods or problems, please share in the comments area.