您的位置:首页 > 其它

LeetCode 4. Median of Two Sorted Arrays

2016-05-05 01:19 351 查看
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

/*
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of two sorted arrays. The overall run time complexity should
be O(lg(m+n)).
*/
/*
There are several methods to solve this problem:
1: merge two array first and get the middle. O(m+n)
2: using two heap (minHeap, maxHeap) to get the middle. (m+n)lg(m+n)
Both algorithms will cost more than O(lg(m+n)).
Probably we need to take advantage of the "sorted" keyword.

Since two arrays are already sorted. That is to say part of the merged sequence
is already sorted.
For example:
nums1 {7, 8, 9}
nums2 {1, 2, 3, 4, 20, 21, 22}.
If we merge them two: {1, 2, 3, 4, 7, 8, 9, 20, 21, 22}.
Thus, subarray {1, 2, 3, 4} is already sorted. {20, 21, 22} and {7, 8, 9} as well.
Maybe, we can use this feature???
We want to find the k position value. to divide the two arrays, we can use:
int pos_m = (m)/(m+n) * k - 1;  value indexes range from 0 to pos_m are in order.
int pos_n = (k-1) - pos_m;   value indexes range from 0 to pos_n are in order.

pos_m + pos_n = (k - 1 - pos_m + pos_m) == k-1. (This range actually include k+1 numbers).

suppose nums1[pos_m] > nums[pos_n - 1] && nums1[pos_m] < nums2[pos_n]
nums1[pos_m] is the one we are looking for! (index starts from 0.)

suppose nums2[pos_n] > nums[pos_m - 1] && nums2[pos_n] < nums1[pos_m]
nums2[pos_n] is the one we are looking for!

Otherwise,
if we know that nums1[pos_m] < nums2[pos_n], the value must be in upper level of nums1.
otherwise, the value must be in upper level of nums2.
*/
 int findMedianSortedArrays(vector<int>& nums1, int m, vector<int>& nums2, n, int pos) {
  if(m <= 0) return nums2[pos - 1];
  if(n <= 0) return nums1[pos - 1];
  int i = (double) n/(m+n) * k - 1;
  int j = k - 1 - i;

  // use INT_MIN and INT_MAX to guard the border.
  int Ai_1 = ((i == 0) ? INT_MIN : nums1[i-1]);
  int Ai == ((i == m) ? INT_MAX : nums1[i]);
  int Bj_1 = ((j == 0) ? INT_MIN : nums2[j-1]);
  int Bj = ((j == n) ? INT_MAX : nums2[j]);

  if(Ai >= Bj_1 && Ai <= Bj) return Ai;
  else if(Bj >= Ai_1 && Bj <= Ai) return Bj;

  if(Ai < Bj) return findMedianSortedArrays(nums1 + i + 1, m-i-1, nums2, n, pos - i - 1);
  else return findMedianSortedArrays(nums1, m, nums2 + j + 1, n - j - 1, pos - j - 1);
}

double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
  int m = nums1.size();
  int n = nums2.size();
  int total = m + n;
  if(total % 2) {
    return (double) findMedianSortedArrays(nums1, m, nums2, n, total / 2);
  } else {
    int a = findMedianSortedArrays(nums1, m, nums2, n, total / 2);
    int b = findMedianSortedArrays(nums1, m, nums2, n, total / 2 + 1);
    return (a + b) / 2.0;
  }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: