4. Median of Two Sorted Arrays
Posted carsonwuu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了4. Median of Two Sorted Arrays相关的知识,希望对你有一定的参考价值。
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)).
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
1 class Solution { 2 public double findMedianSortedArrays(int[] nums1, int[] nums2) { 3 int n1 = nums1.length; 4 int n2 = nums2.length; 5 if ((n1 + n2) % 2 == 1) { 6 return findNumK(nums1, n1, nums2, n2, (n1 + n2) / 2 + 1); 7 } else { 8 return (findNumK(nums1, n1, nums2, n2, (n1 + n2) / 2) + findNumK(nums1, n1, nums2, n2, (n1 + n2) / 2 + 1)) 9 / 2; 10 } 11 } 12 13 public double findNumK(int[] nums1, int n1, int[] nums2, int n2, int k) { 14 if (n1 > n2) { 15 return findNumK(nums2, n2, nums1, n1, k); 16 } 17 if (n1 == 0) { 18 return nums2[k - 1]; 19 } 20 if (k == 1) { 21 return Math.min(nums1[0], nums2[0]); 22 } 23 int temp1 = Math.min(k / 2, n1); 24 int temp2 = k - temp1; 25 if (nums1[temp1 - 1] < nums2[temp2 - 1]) { 26 return findNumK(subArray(nums1, temp1), n1 - temp1, nums2, n2, k - temp1); 27 } else if (nums1[temp1 - 1] > nums2[temp2 - 1]) { 28 return findNumK(nums1, n1, subArray(nums2, temp2), n2 - temp2, k - temp2); 29 } else { 30 return nums1[temp1 - 1]; 31 } 32 } 33 34 public int[] subArray(int[] a, int b) { 35 int[] temp = new int[a.length - b]; 36 for (int i = 0; i < a.length - b; i++) { 37 temp[i] = a[b + i]; 38 } 39 return temp; 40 } 41 }
以上是关于4. Median of Two Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-4 Median of Two Sorted Arrays
4. Median of Two Sorted Arrays