4. Median of Two Sorted Arrays

題目連接:https://leetcode.com/problems/median-of-two-sorted-arrays/description/算法

題目大意:給出兩個有序數組,找出他們的中位數,若是是偶數,要計算兩個最中間的數的均值。數組

法一:模擬歸併排序的核心算法,將兩個有序數組合成一個有序數組,時間複雜度o(n),而後直接從獲得的數組中拿到中間值。代碼以下(耗時117ms):ide

 1     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 2         int length1 = nums1.length, length2 = nums2.length;
 3         int[] res = new int[length1 + length2];
 4         int index = 0, index1 = 0, index2 = 0;
 5         for( ; index1 < length1 && index2 < length2; ) {
 6             if(nums1[index1] < nums2[index2]) {
 7                 res[index++] = nums1[index1++];
 8             }
 9             else if(nums1[index1] > nums2[index2]) {
10                 res[index++] = nums2[index2++];
11             }
12             else {
13                 res[index++] = nums1[index1++];
14                 res[index++] = nums2[index2++];
15             }
16         }
17         while(index1 < length1) {
18             res[index++] = nums1[index1++];
19         }
20         while(index2 < length2) {
21             res[index++] = nums2[index2++];
22         }
23         double ans = 0;System.out.println(index);
24         if(index % 2 == 0) {
25             ans = (double) (res[index / 2] + res[index / 2 - 1]) / 2;
26         }
27         else {
28             ans = res[index/2];
29         }
30         return ans;
31     }
View Code

還有好多別的解法,尷尬,看不懂spa

http://windliang.cc/2018/07/18/leetCode-4-Median-of-Two-Sorted-Arrays/code

相關文章
相關標籤/搜索