4. Median of Two Sorted Arrays
Posted hyxsolitude
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)).
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
1 class Solution { 2 3 public double findMedianSortedArrays(int[] nums1, int[] nums2) { 4 int m = nums1.length, n = nums2.length; 5 int mid = (m + n) / 2 + (m + n) % 2; 6 int pos1 = -1, pos2 = -1; 7 while (mid > 0) { 8 int temp = mid / 2 + mid % 2; 9 if (pos2 + temp >= n || 10 (pos1 + temp < m && nums1[pos1 + temp] < nums2[pos2 + temp])) { 11 pos1 += temp; 12 } else { 13 pos2 += temp; 14 } 15 mid -= temp; 16 } 17 18 19 20 double ans = 0; 21 if (pos2 == -1 || (pos1 != -1 && nums1[pos1] >= nums2[pos2])) { 22 ans = nums1[pos1]; 23 } else { 24 ans = nums2[pos2]; 25 } 26 if ((m + n) % 2 == 0) { 27 double temp; 28 if (pos2 + 1 >= n || 29 (pos1 + 1 < m && nums1[pos1 + 1] < nums2[pos2 + 1])) 30 temp = nums1[pos1 + 1]; 31 else { 32 temp = nums2[pos2 + 1]; 33 } 34 ans = (ans + temp) / 2 ; 35 } 36 return ans; 37 38 } 39 }
以上是关于4. Median of Two Sorted Arrays的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-4 Median of Two Sorted Arrays
4. Median of Two Sorted Arrays