leetcode_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
我的答案:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {int m = nums1.size();int n = nums2.size();if (m == 0){if (n == 0)return 0.0;elsereturn n % 2 == 0 ? double(nums2[n / 2] + nums2[n / 2 - 1]) / 2.0 : double(nums2[n / 2]);}else{if (n == 0)return m % 2 == 0 ? double(nums1[m / 2] + nums1[m / 2 - 1]) / 2.0 : double(nums1[m / 2]);}int N = m + n;int flag;if (N % 2 == 0)flag = 0;elseflag = 1;int mid = N / 2;int a1, a2 = 0;int i = 0, j = 0, count = 0;if (nums1[0] <= nums2[0]){a1 = nums1[0];i++;}else{a1 = nums2[0];j++;}while ((i<m) && (j<n)){if (count == mid){if (flag == 0)return double(a1 + a2) / 2.0;elsereturn double(a1);}a2 = a1;if (nums1[i] <= nums2[j]){a1 = nums1[i];i++;}else{a1 = nums2[j];j++;}count++;}while (i < m){if (count == mid){if (flag == 0)return double(a1 + a2) / 2.0;elsereturn double(a1);}a2 = a1;a1 = nums1[i];i++;count++;}while (j < n){if (count == mid){if (flag == 0)return double(a1 + a2) / 2.0;elsereturn double(a1);}a2 = a1;a1 = nums2[j];j++;count++;}if (flag == 0)return double(a1 + a2) / 2.0;elsereturn double(a1); }思路解析:
? ? ? 首先先不考慮一些比較特殊的情況,考慮兩個已排序的數組長度都是大于0的,這個題目的目標就是要找到兩個已經排序的數組在放在一塊排序之后最中間的一個或者兩個數的平均值(如果總長度是奇數,就是中間的那個值,如果總長度是偶數,就是中間兩個值的平均值),我們不需要對兩個數組重新排序,只需要不斷比較這兩個數組中的值進行排序,并記錄比較的次數,拿兩個變量a1,a2記錄本次與上次比較的結果,當比較次數達到總長度的一半的時候,那兩個變量拿兩個變量a1,a2記錄的值就是我們找到的總序列的中間值,再判讀整個序列長度是奇數或者偶數,以此來計算中間值median。這里的特殊情況就是兩個數組中有一個是空數組或者兩個都是空數組等情況,只要單獨處理即可。
總結
以上是生活随笔為你收集整理的leetcode_median of two sorted arrays的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode_longest sub
- 下一篇: python中iloc的详细用法_pyt