如何在 O(1) 中使用 set(i, ele)、add()、remove() 方法制作列表?

问题描述

作为标题,我想在 O(1) 中创建一个包含 set(i,ele)add(ele) (at front or at the end)remove(ele) (at font or at the end) 的列表。 如果我们使用链表,很容易在 O(1) 中进行 add() 和 remove() 操作。但是对于链表,我们无法访问 O(1) 中的第 i 个元素。

根据评论,我应该指定 add or remove 方法只在前面或最后工作。

提前致谢。

解决方法

你可以使用哈希表:插入、删除和搜索平均都是 O(1),最坏情况是 O(n)

https://en.wikipedia.org/wiki/Hash_table

,

在 C++ 中,您可以使用 Vector 容器来插入、添加、删除:

#include <vector>
#include <iostream>

using namespace std;

void print_vector(vector<int> v) {
    for (auto & n : v)
            cout << n << ' ';
    cout << endl;
}

int main(void) {
    vector<int> v = {3,5,6,7};

    print_vector(v);
    v.push_back(8); // add at end of vector
    print_vector(v);

    if (v.size()) // protection
        v.pop_back(); // remove at end of vector
    print_vector(v);

    int i = 3;
    if (v.size <= i) // protection
        v.insert(v.begin() + i,42); // insert 42 at index i
    print_vector(v);
    return 0;
}

输出:

3 5 6 7 
3 5 6 7 8 
3 5 6 7 
3 5 6 42 7