首页 > 编程语言 > 详细

[leetcode]4. Median of Two Sorted Arrays俩有序数组的中位数

时间:2019-04-03 14:58:34      阅读:139      评论:0      收藏:0      [点我收藏+]

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)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:

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

The median is 2.0

Example 2:

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

The median is (2 + 3)/2 = 2.5

 

Solution1: time complexity is O(m+n). merge two sorted array, then find the median

技术分享图片

技术分享图片

code:

 1 /*
 2   Time Complexity:  O(m+n)
 3   Space Complexity: O(m+n) 
 4 */
 5 
 6 class Solution {
 7     public double findMedianSortedArrays(int[] nums1, int[] nums2) {
 8         int[] mergedArray = mergeTwoSortedArray(nums1, nums2);
 9         int n = mergedArray.length; 
10         if( n % 2 == 0){
11             return (mergedArray[(n-1)/2] + mergedArray[n/2])/2.0; 
12         }else{
13             return mergedArray[n/2]; 
14         }
15     } 
16     
17     public int[] mergeTwoSortedArray(int[] nums1, int[] nums2){
18         int[] merged = new int[nums1.length + nums2.length];
19         int i = 0, j = 0, k = 0;
20         // 两个array同时扫
21         while( i < nums1.length && j < nums2.length){
22             merged[k++] = (nums1[i] < nums2[j]) ? nums1[i++] : nums2[j++]; 
23         }
24         //扫到只剩下较长的那个array, either nums1 or nums2
25         while ( i < nums1.length ){
26              merged[k++] = nums1[i++];
27         }
28         while(j < nums2.length){
29             merged[k++] = nums2[j++];
30         }
31         return merged;
32     }
33 }

 

Solution2: time complexity is O(log (m+n)). 

[leetcode]4. Median of Two Sorted Arrays俩有序数组的中位数

原文:https://www.cnblogs.com/liuliu5151/p/10648755.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!