LeetCode 4. Median of Two Sorted Arrays(数组, 查找)

LeetCode 4. Median of Two Sorted Arrays(数组, 查找)

Tags:
- Binary Search
- Array
- Divide and Conquer

问题描述

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

解题思路

题意是给出两个排序好的数组,求中值。
第一个想到的方法是先将数组合并到一个数组中,然后取中值。但是时间复杂度为O(m+n),题目要求O(log (m+n))

可以将问题转化成求两个数组中求第k大的数,每次都删除一半比k小的数,类似二分查找。这样时间复杂度可以达到O(log(m+n))
两个数组为A和B,假设他们的元素个数都大于k/2(如果小于k/2, 那直接将这个数组末尾最大的数放入比较。)
A[k/2-1]B[k/2-1]进行比较,有以下三种情况

  • A[k/2-1] < B[k/2-1] : A[0]到A[k/2-1]都小于第k个数,可以删除
  • A[k/2-1] > B[k/2-1] : B[0]到B[k/2-1]都小于第k个数,可以删除
  • A[k/2-1] == B[k/2-1] : 找到了第k大的数,直接返回A[k/2-1]

接着写一个递归函数,返回第k大的数,控制一些终止条件
- 当A或B是空的,直接返回B[k-1]或者A[k-1]
- 当k = 1,返回min(A[0], B[0])
- 当A[k/2-1] == B[k/2-1],返回A[k/2-1]或者B[k/2-1]

参考代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
        const int s1 = nums1.size(), s2 = nums2.size();
        int s = s1 + s2;
        if (s % 2 == 1)
            return find_kth(nums1.cbegin(), s1, nums2.cbegin(), s2, s / 2 + 1);
        else
            return (find_kth(nums1.cbegin(), s1, nums2.cbegin(), s2, s / 2) +
                find_kth(nums1.cbegin(), s1, nums2.cbegin(), s2, s / 2 + 1)) / 2.0;
    }

private:
    int find_kth(vector<int>::const_iterator A, int m, 
        vector<int>::const_iterator B, int n, int k)
    {
        if (m > n) return find_kth(B, n, A, m, k);
        if (m == 0) return *(B + k - 1);
        if (k == 1) return min(*A, *B);

        // divide k into two parts
        int ia = min(k / 2, m), ib = k - ia;
        if (*(A + ia - 1) < *(B + ib - 1))
            return find_kth(A + ia, m - ia, B, n, k - ia);
        else if (*(A + ia - 1) > *(B + ib - 1))
            return find_kth(A, m, B + ib, n - ib, k - ib);
        else
            return A[ia - 1];
    }
};

int main()
{
    vector<int> nums1 = {1, 3, 5, 7, 9};
    vector<int> nums2 = {2, 4, 6, 8, 10};
    auto sl = Solution();
    cout << sl.findMedianSortedArrays(nums1, nums2) << endl;

    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值