PAT 甲级 1029 Median

PAT 甲级 1029 Median

#include <bits/stdc++.h>
using namespace std;
int main()
{
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
#endif
    // Input
    int n;
    cin >> n;
    vector<long long> nums1(n);
    for (auto& i : nums1) cin >> i;
    cin >> n;
    vector<long long> nums2(n);
    for (auto& i : nums2) cin >> i;
    // 中位数坐标
    int target = (nums1.size() + nums2.size() - 1) / 2;
    // 合并输出,好写但O((m+n)log(m+n))
    // vector<long long> nums;
    // nums.insert(nums.end(), nums1.begin(), nums1.end());
    // nums.insert(nums.end(), nums2.begin(), nums2.end());
    // sort(nums.begin(), nums.end());
    // cout << nums[target];
    // two pointer,归并的方式计数或者直接归并,O(m+n)
    int i = 0, j = 0, index = 0;
    long long ans;
    // 归并过程
    while (i < nums1.size() && j < nums2.size()) {
        if (nums1[i] < nums2[j]) {
            if (index == target) { ans = nums1[i]; }
            ++i, ++index;
        }
        else {
            if (index == target) { ans = nums2[j]; }
            ++j, ++index;
        }
    }
    // 剩余元素
    while (i < nums1.size()) {
        if (index == target) { ans = nums1[i]; }
        ++i, ++index;
    }
    while (j < nums2.size()) {
        if (index == target) { ans = nums2[j]; }
        ++j, ++index;
    }
    cout << ans;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值