4.、Median of Two Sorted Arrays(兩個有序序列的中位數)
阿新 • • 發佈:2019-01-10
題目要求在給定兩個長度分別為m和n的有序序列時,找出這兩個序列合起後的中位數。並且要求時間複雜度為O(log(m+n))。
首先,中位數的定義是,當序列長度為偶數時,中位數的值為序列中間兩個數的均值;當序列為奇數時,中位數為正中間的數。當序列長度為n時,其值分別為(array[n/2]+array[n/2-1])/2、array[n/2]。為了達到時間複雜度的要求,故採用兩個索引分別同時遍歷兩個序列,並且用last和cur來記錄當前值和上一個值,當cur記錄的值的索引為(n/2)時,則跳出迴圈。具體求解,如程式碼所示:
C++:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int len1 = nums1.size(); int len2 = nums2.size(); int last = 0,cur = 0; int mid = (len1+len2)/2; int k = 0,i = 0,j = 0; while(k <= mid) { last = cur; if(i == len1) { cur = nums2[j]; j++; } else if(j == len2) { cur = nums1[i]; i++; } else if(nums1[i] < nums2[j]) { cur = nums1[i]; i++; } else { cur = nums2[j]; j++; } k++; } return (len1+len2)%2?cur:double(last+cur)/2; }
python:
def findMedianSortedArrays(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: float """ last = 0 cur = 0 len1 = len(nums1) len2 = len(nums2) mid = (len1 + len2)/2 i = 0 j = 0 k = 0 while(k <= mid): last = cur if i == len1: cur = nums2[j] j = j + 1 elif j == len2: cur = nums1[i] i = i + 1 elif nums1[i] < nums2[j]: cur = nums1[i] i = i + 1 else: cur = nums2[j] j = j + 1 k = k + 1 if (len1+len2)%2: return cur else: return (last+cur)/2.0