LeetCode上求两个排序数组中位数问题—— Median of Two Sorted Arrays
1.題目
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:
Example 2:
2.中文翻譯
有兩個大小分別為m和n的排序數(shù)組nums1和nums2。
查找兩個排序數(shù)組的中位數(shù)。 總的運行時間復(fù)雜度應(yīng)該是O(log(m + n))。
例1:
nums1 = [1,3]
nums2 = [2]
中位數(shù)是2.0
例2:
nums1 = [1,2]nums2 = [3,4]
中位數(shù)是(2 + 3)/ 2 = 2.5
3.解題思路
合并:在這里,因為規(guī)定了時間復(fù)雜度,因此我們要充分利用這一點,又因為是排序數(shù)組,在C語言數(shù)據(jù)結(jié)構(gòu)中我們學(xué)過兩個排序鏈表的合并,其復(fù)雜度為O(log2(m+n));因此,這里采取空間換時間的策略,構(gòu)建一個新的數(shù)組nums[],將nums1和nums2比較,從第一個開始,若nums1元素小于nums2元素,放入新數(shù)組nums中,然后nums1往后移動一個位置,大于則放入nums2元素,同樣往后移動,當(dāng)nums1和nums2有一個數(shù)組移動完成,則將另一個數(shù)組中剩下元素移入nums數(shù)組中。
求中位數(shù):中位數(shù)在奇數(shù)和偶數(shù)時取值不同,奇數(shù)數(shù)組為最中間一個,偶數(shù)為中間兩個和的一半,根據(jù)合并后nums長度來求種中位數(shù)
4.算法如下
?public double findMedianSortedArrays(int[] nums1, int[] nums2) {
? ? ? double low,high,mid=0;
? ? ? int nums[]=new int[nums1.length+nums2.length];
? ? ? int i=0,j=0,k=0;
? ? ? while (i<nums1.length&&j<nums2.length) { ? //兩數(shù)組都有元素時
if (nums1[i]<nums2[j]) { ??
nums[k++]=nums1[i++]; ? ?//比較完一次往后移動一位
}
else {
nums[k++]=nums2[j++];
}
}
? ? ? while (i<nums1.length) ? ? //nums2數(shù)組比較完
? ? ?nums[k++]=nums1[i++];
? ? ? while(j<nums2.length) ? ?//nums1數(shù)組比較完
? ? ?nums[k++]=nums2[j++];
? ? ??
? ? ? if ((nums.length%2)==0) { ? ? ?//數(shù)組長度為偶數(shù)情況下
low=(double)nums[nums.length/2];
high=(double)nums[(nums.length/2)-1];
mid=(low+high)/2;
}
? ? ? else {
mid=(double)nums[nums.length/2]; ?//數(shù)組長度為奇數(shù)情況下
}
? ? ??
? ? ? return mid;
? ? }
5.LeetCode上提交結(jié)果
總結(jié)
以上是生活随笔為你收集整理的LeetCode上求两个排序数组中位数问题—— Median of Two Sorted Arrays的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode上求最长公共字符前缀字符
- 下一篇: LeetCode上删除链表末尾第N个节点