4. Median of Two Sorted Arrays

题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/description/

题目大意:给出两个有序数组,找出他们的中位数,如果是偶数,要计算两个最中间的数的均值。

法一:模拟归并排序的核心算法,将两个有序数组合成一个有序数组,时间复杂度o(n),然后直接从得到的数组中拿到中间值。代码如下(耗时117ms):

 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

还有好多别的解法,尴尬,看不懂

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

原文地址:https://www.cnblogs.com/cing/p/7839605.html