4.尋找兩個有序數組的中位數(Median of Two Sorted Arrays)
前言
由于,我感覺代碼框不怎麼好看,然後想自定義一個背景。然後就試着去寫了下:
<link href="/css/blockquote.css" target="_blank" rel="external nofollow" rel=“stylesheet” type=“text/css” >
在source建立了css檔案夾,然後建立了相應的css檔案。
在引用中加入span标簽,寫結果,就可以用span的樣式(加粗)效果。
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)).
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
給定兩個大小為 m 和 n 的有序數組 nums1 和 nums2。
請你找出這兩個有序數組的中位數,并且要求算法的時間複雜度為 O(log(m + n))。
你可以假設 nums1 和 nums2 不會同時為空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
則中位數是 2.0
思路
直接用将兩個清單合并,排序後,找到下标位置。然後傳回。
清單合并有兩種方式:
- nums = nums1 + nums2 生成新的對象nums
- nums1.extend(nums2) 在原有的nums1上擴充
def findMedianSortedArrays(self, nums1, nums2):
#清單合并
nums = sorted(nums1+nums2)
if len(nums)%2 ==0:
answer = (nums[int(len(nums)/2-1)]+nums[int(len(nums)/2)])/2
else:
answer = nums[int((len(nums)+1)/2)-1]
return answer
leetcode官網上給了一個解決問題的思路,還沒怎麼看懂,以後再看。
作者:無涯明月
原文位址:http://baiyazi.top/2019/leetcode-4/