码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-15 21:03:31      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:class   article   复杂度   bsp   double   amp   数组   分治   tps   


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

给定两个大小为 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 }

 

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

标签:class   article   复杂度   bsp   double   amp   数组   分治   tps   

原文地址:https://www.cnblogs.com/rainbow-/p/10274165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!