原題信息:
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.0Example 2:
nums1 = [1, 2]nums2 = [3, 4]The median is (2 + 3)/2 = 2.5我自己的理解:有兩個(gè)有序的數(shù)組nums1和nums2,長(zhǎng)度分別為m和n。找到兩個(gè)有序數(shù)組的中間值。整個(gè)運(yùn)行的時(shí)間復(fù)雜度為O(log(m+n))。然后在看看題目中給的兩個(gè)例子,大致思路就有了。
【分析】:
(1)首先把兩個(gè)有序數(shù)組合并成一個(gè)數(shù)組。
(2)在對(duì)合并的數(shù)組進(jìn)行排序。
(3)找出合并后數(shù)組的中間值,即為所求答案。
下面是可以AC的java代碼:
package test;import java.util.Arrays;public class MedianOfTwoSortedArrays { public static void main(String[] args) { int[] a={1,2}; int[] b={3,4}; MedianOfTwoSortedArrays medianOfTwoSortedArrays=new MedianOfTwoSortedArrays(); System.out.PRint(medianOfTwoSortedArrays.findMedianSortedArrays(a, b)); } public double findMedianSortedArrays(int[] nums1, int[] nums2) { int[] combine=concat(nums1,nums2); Arrays.sort(combine); //合并后的數(shù)組進(jìn)行排序 if((0+combine.length-1)%2==0){ return (double)combine[(combine.length-1)/2]; }else { int temp=(combine.length-1)/2; return (double)(combine[temp]+combine[temp+1])/2; } } /** * 將兩個(gè)有序的數(shù)組合并成一個(gè)數(shù)組 * @param first 第一個(gè)數(shù)組 * @param second 第二個(gè)數(shù)組 * @return 合并后的數(shù)組 */ public int[] concat(int[] first,int[] second){ int[] sum=new int[first.length+second.length]; System.arraycopy(first, 0, sum, 0, first.length); System.arraycopy(second, 0, sum, first.length, second.length); return sum; }}當(dāng)然AC了,還是要多看看高手們的代碼,看看自己還差多遠(yuǎn)。這不看不知道,一看還看出問(wèn)題了。題目要求的時(shí)間復(fù)雜度是O(log(m+n))。我分析了自己上邊的代碼時(shí)間復(fù)雜度是O(nlogn)。寫(xiě)的這個(gè)算法不是很?chē)?yán)謹(jǐn)呢!所以,抱著科學(xué)要嚴(yán)謹(jǐn)?shù)膽B(tài)度,我又寫(xiě)了另外一種算法。【思路】把本題的問(wèn)題轉(zhuǎn)換成求第k小數(shù)的問(wèn)題。這個(gè)解題思路 ,網(wǎng)上有很多詳細(xì)的解析,我就不詳細(xì)寫(xiě)了。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注