LeetCode 第4题 寻找有序数组的中位数


/*
寻找两个有序数组的中位数

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。

请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

你可以假设 nums1 和 nums2 不会同时为空。

示例 1:

nums1 = [1, 3]
nums2 = [2]

则中位数是 2.0
示例 2:

nums1 = [1, 2]
nums2 = [3, 4]

则中位数是 (2 + 3)/2 = 2.5
*/


/*
自己实现的只是简单代码.

分治解法 : https://blog.csdn.net/hk2291976/article/details/51107778
*/

 1 class Solution4 {
 2 
 3   public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 4     int sumLength = nums1.length + nums2.length;
 5     int pos1 = 0;
 6     int pos2 = 0;
 7     int currPos = 0;
 8     double[] arr = new double[(sumLength >> 1) + 1];
 9 
10     while (currPos < ((nums1.length + nums2.length >> 1) + 1)) {
11       if (pos1 == nums1.length) {
12         arr[currPos] = nums2[pos2++];
13       } else if (pos2 == nums2.length) {
14         arr[currPos] = nums1[pos1++];
15       } else if (nums1[pos1] < nums2[pos2]) {
16         arr[currPos] = nums1[pos1++];
17       } else {
18         arr[currPos] = nums2[pos2++];
19       }
20       ++currPos;
21     }
22     if ((sumLength & 1) == 1) {
23       return arr[currPos - 1];
24     } else {
25       return (arr[currPos - 1] + arr[currPos - 2]) / 2;
26     }
27   }
28 }

 

posted @ 2019-01-15 20:36  散装英语king  阅读(301)  评论(0编辑  收藏  举报