leetcode | Median of Two Sorted Arrays (Python)
程序员文章站
2022-03-23 17:33:07
...
本题思路比较简单。
学习了extend()和append()的不同之处。
num1 = [5,2]
num2 = [3,4]
num1.extend(num2) #extend()
print (num1)
num1 = [5,2]
num1.append(num2) #append()
print (num1)
JacobdeMacbook-Air:~ Jacob$ python3 -u "/Users/Jacob/Desktop/test.py"
[5, 2, 3, 4]
[5, 2, [3, 4]]
class Solution:
def findMedianSortedArrays(self, nums1: list, nums2: list) -> float:
nums1.extend(nums2)
nums1.sort()
if len(nums1)%2 == 0:
median = (nums1[int((len(nums1)-1)/2)] + nums1[int((len(nums1)-1)/2) +1]) / 2
#如果长度为偶数
else:
median = nums1[int(len(nums1)/2)]
#如果长度为奇数
return median
num1 = [5,2]
num2 = [3,4]
print (Solution().findMedianSortedArrays(num1,num2))