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;
}
相关推荐
风影同志7832421 分钟前
20 个比特能装下多少行情?——实测拆解 Kronos 的 K 线分词器
算法
写的都是BUG1 小时前
APK 里的钥匙,一直就放在门口:聊聊加固真正该做什么
前端·算法
地平线开发者1 小时前
CLIP 的零样本分类:一组文本如何变成图像分类器?
算法
京东云开发者2 小时前
从“会生成”到“能生产”:萤火虫 AIGC 平台的 AI Infra 实践
算法·aigc·产品
youshi66682 小时前
PID——算法改进
算法
一只不想敲代码的程序猿3 小时前
如何更高效地拆解问题?
算法
微尘hjx4 小时前
【Deep-OC-SORT 02】多轨迹算法Deep-OC-SORT-相对 OC-SORT 的改进点
人工智能·算法·yolo·目标跟踪·视觉检测·ultralytics·deep-oc-sort
梦帮科技4 小时前
意识启发式量子隧穿退火算法用于全局优化 (CITA) 完整技术指南
网络·人工智能·算法·量子计算·模拟退火算法
一去不复返的通信er6 小时前
排序 + 双指针:力扣15三数之和
算法·leetcode
Pniubi6 小时前
力扣3无重复字符的最长字串(滑动窗口)
算法·leetcode·职场和发展