vector如何实现有序数组?

有序数组维护一个序列 a 1 , a 2 , . . . , a n a_1,a_2,...,a_n a1,a2,...,an,使得其保持有序,而且支持插入时间为 O ( l o g n ) O(logn) O(logn)的操作。python中有第三方库SortedList,C++并没有这样的stl库。

但我们可以使用vector和lower_bound进行类似的操作:使用lower_bound找到插入的位置,使用vector::insert插入该位置。

如题 洛谷P1168 中位数

正统的做法是维护一个最大堆和一个最小堆,最小堆的数在后半部分(比最大堆大),最大堆的数在前半部分,每次取最大堆的堆顶。但是写起来比较麻烦。

用有序数组可以这么写:

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <unordered_map>
#include <algorithm>
#define LT(x) (x * 2)
#define RT(x) (x * 2 + 1)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;

int n;
int a[100002];
vi b;   // 有序数组


int main() {
    //freopen("in.txt", "r", stdin);
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
    }
    int m = (n + 1) / 2;
    b.push_back(a[0]);
    printf("%d\n", a[0]);
    for (int i = 1; i < m; ++i) {
        int pos = lower_bound(b.begin(), b.end(), a[i * 2 - 1]) - b.begin();
        b.insert(b.begin() + pos, a[i * 2 - 1]);
        pos = lower_bound(b.begin(), b.end(), a[i * 2]) - b.begin();
        b.insert(b.begin() + pos, a[i * 2]);
        printf("%d\n", b[i]);
    }
    return 0;
}
相关推荐
苦藤新鸡6 分钟前
39.二叉树的直径
算法·leetcode·深度优先
TracyCoder12327 分钟前
LeetCode Hot100(6/100)——15. 三数之和
算法·leetcode
bubiyoushang88827 分钟前
基于传统材料力学势能法的健康齿轮时变啮合刚度数值分析
人工智能·算法
星火开发设计30 分钟前
const 指针与指针 const:分清常量指针与指针常量
开发语言·c++·学习·算法·指针·const·知识
闻缺陷则喜何志丹31 分钟前
【树 链 菊花】P10418 [蓝桥杯 2023 国 A] 相连的边|普及+
c++·算法·蓝桥杯···菊花
ygklwyf1 小时前
JPRS编程竞赛2026#1(AtCoder初学者竞赛442)
c++·算法·模拟
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #21:合并两个有序链表(迭代法、原地合并法等多种实现方案详解)
算法·leetcode·链表·优先队列·迭代法·合并两个有序链表·原地合并
源代码•宸1 小时前
Leetcode—47. 全排列 II【中等】
经验分享·后端·算法·leetcode·面试·golang·深度优先
wen__xvn1 小时前
基础算法集训第20天:Dijkstra
算法·图论
Yiyaoshujuku2 小时前
疾病的发病率、发病人数、患病率、患病人数、死亡率、死亡人数查询网站及数据库
数据库·人工智能·算法