原題信息:
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我自己的理解:有兩個有序的數組nums1和nums2,長度分別為m和n。找到兩個有序數組的中間值。整個運行的時間復雜度為O(log(m+n))。然后在看看題目中給的兩個例子,大致思路就有了。
【分析】:
(1)首先把兩個有序數組合并成一個數組。
(2)在對合并的數組進行排序。
(3)找出合并后數組的中間值,即為所求答案。
下面是可以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); //合并后的數組進行排序 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; } } /** * 將兩個有序的數組合并成一個數組 * @param first 第一個數組 * @param second 第二個數組 * @return 合并后的數組 */ 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; }}當然AC了,還是要多看看高手們的代碼,看看自己還差多遠。這不看不知道,一看還看出問題了。題目要求的時間復雜度是O(log(m+n))。我分析了自己上邊的代碼時間復雜度是O(nlogn)。寫的這個算法不是很嚴謹呢!所以,抱著科學要嚴謹的態度,我又寫了另外一種算法。【思路】把本題的問題轉換成求第k小數的問題。這個解題思路 ,網上有很多詳細的解析,我就不詳細寫了。
新聞熱點
疑難解答