Leetcode problem 4:Median of Two Sorted Arrays

Description

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

Solution

  • Median(中位数): 概念起源于统计学和概率论,对于一个列表,如果列表里元素的个数为奇数,则取中间的那个;如果元素的个数为偶数,则取最中间两个元素的平均值。

  • 本地思路:本题可以衍生为更为一般性的问题,对于两个递增序列,我们可以找到新数组第k个元素。这里采用归并计数算法合并数组。

Code

/**
 * Leetcode problem 4: Find median of two sorted arrays;
 *
 * hellfire (asyncloading#163.com)
 * Feb 18th, 2016
 */
#include<iostream>
#include<vector>

using namespace std;

class Solution {
  public:

    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
      int m = nums1.size();
      int n = nums2.size();
      int total = m + n;
      if (total % 2 == 0)
      {
        return (findKth(nums1, nums2, total / 2) + findKth(nums1, nums2, total / 2 + 1)) / 2.0;
      }
      else
      {
        return findKth(nums1, nums2, (total + 1) / 2) * 1.0;
      } 
    }
    /* Merge and counting. */
    int findKth(vector<int>& nums1, vector<int>& nums2, int k)
    {
      int p = 0, q = 0;
      for (int i = 0; i < k - 1; i ++)
      {
        /* Handle pointer overflow. */
        if (p >= nums1.size())
        {
          q ++;
        }
        else if (q >= nums2.size())
        {
          p ++;
        }
        else if (nums1[p] <= nums2[q])
        {
          p ++;
        }
        else
        {
          q ++;
        }
      }
      if (p >= nums1.size())
      {
        return nums2[q];
      }
      else if (q >= nums2.size())
      {
        return nums1[p];
      }
      else
      {
        return min(nums1[p], nums2[q]);
      }
    }

};

int main(int argc, char **argv)
{
  int arr1[] = {1, 3, 5, 7, 9};
  int arr2[] = {2, 4, 6};
  vector<int> nums1(arr1 + 0, arr1 + 5);
  vector<int> nums2(arr2 + 0, arr2 + 3);
  Solution s;
  double result = s.findMedianSortedArrays(nums1, nums2);

  cout << result << endl;
}

Github源代码:https://github.com/oj-problem/leetcode/blob/master/solution4.cpp

备注

本题可以采用效率更高的二分法,时间复杂度可以达到 O(log (m+n))。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值