1. 程式人生 > >[leetcode]4. Median of Two Sorted Arrays倆有序數組的中位數

[leetcode]4. Median of Two Sorted Arrays倆有序數組的中位數

span size double width ret merge 圖片 bubuko complex

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倆有序數組的中位數