1029. Median (25)

可能做了假题,这道题明显该merge,对两个有序序列进行合并,结果sort一下居然过了,也贴一下merge

sort

#include<iostream>
#include<vector>
#include<algorithm>
#pragma warning (disable:4996)
using namespace std;
vector<long int> a;
int N;
int main()
{
    cin >> N;
    for (int t = 0;t < N;t++)
    {
        long int temp;
        scanf("%ld", &temp);
        a.push_back(temp);
    }
    cin >> N;
    for (int t = 0;t < N;t++)
    {
        long int temp;
        scanf("%ld", &temp);
        a.push_back(temp);
    }
    sort(a.begin(), a.end());
    cout << a[(a.size() - 1) / 2] << endl;

}

merge

#include<iostream>
#pragma warning (disable:4996)
#include<stdlib.h>
int main()
{
    int N, M;
    scanf("%d", &N);
    int *s = (int *)malloc(sizeof(int)*N);
    for (int t = 0;t < N;t++)
        scanf("%d", s + t);
    scanf("%d", &M);
    s = (int *)realloc(s,sizeof(int)*(M + N));
    for (int t = N;t < M + N;t++)
        scanf("%d", s + t);
    int i = 0, j = N;
    int *temp= (int *)malloc(sizeof(int)*(N+M));
    int t = 0;
    while (i < N&&j < M + N)
    {
        if (s[i] < s[j])
            temp[t++] = s[i++];
        else
            temp[t++] = s[j++];
    }
    while (i < N)
        temp[t++] = s[i++];
    while (j < M + N)
        temp[t++] = s[j++];
    printf("%d\n", temp[(M + N - 1) / 2]);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值