算法 - 在两个有序数组中寻找第k大元素

题目:

数组A,A的长度m,数组B,B的长度n,需要找第K大的数。

要求:时间复杂度log(m+n)

思路

确定第K大的数前面的K-1个数,同时要考虑极端情况

解法

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

int findTheKthElementInTwoSortedArray01(int A[], int m, int B[], int n, int kth)
{
    if (kth > (m+n)) {
        return -1;
    }
    if(m > n) {
        return findTheKthElementInTwoSortedArray01(B, n, A, m, kth);
    }
    if (kth == 1) {
        return std::min(A[0], B[0]);
    }
    if (m == 0) {
        return B[kth-1];
    }

    //分割k
    int ia = std::min(kth/2, m);
    int ib = kth - ia;

    if (A[ia-1] < B[ib-1]) {
        return findTheKthElementInTwoSortedArray01(A+ia, m-ia, B, n, kth-ia);
    }
    if (A[ia-1] > B[ib-1]) {
        return findTheKthElementInTwoSortedArray01(A, m, B+ib, n-ib, kth-ib);
    }

    return A[ia-1];
}


int main()
{
    vector<int> t1{1, 3, 8, 9};
    vector<int> t2{};
    int kth = 4;
    //vector<int> t2{2, 5, 7, 15, 20};
    int arr[t1.size()];
    int brr[t2.size()];
    std::copy(t1.begin(), t1.end(), arr);
    std::copy(t2.begin(), t2.end(), brr);
    int ret = findTheKthElementInTwoSortedArray01(arr, t1.size(), brr, t2.size(), kth);
    cout << ret <<endl;
    return 0;
}

扩展: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

寻找数组的中位数的小技巧:假设数组的长度是m,找第(m+1)/2位和第(m+2)/2位的元素,两者的平均数即为数组的中位数。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值