简体   繁体   English

使用O(1)运行时从向量中删除元素

[英]removing elements from a vector with O(1) runtime

"Write a function which takes as an input an object of vector type removes an element at the rank k in the constant time, O(1) [constant]. Assume that the order of elements does not matter." “编写一个函数,它将矢量类型的对象作为输入,在常数时间中删除等级k处的元素,O(1)[常量]。假设元素的顺序无关紧要。”

I thought I might have had an idea about this. 我想我可能对此有所了解。 But, as I started to try by using .erase(), I looked up what the big-O notation was and found out it was O(n),as in linear relation. 但是,当我开始尝试使用.erase()时,我查找了大O符号,并发现它是O(n),就像线性关系一样。 I can't think of any other way at the moment. 我现在想不出任何其他方式。 I don't want any code, but I think pseudo code will at least point me in the right direction if anyone can help 我不想要任何代码,但我认为如果有人可以提供帮助,伪代码至少会指向正确的方向

Assume that the order of elements does not matter. 假设元素的顺序无关紧要。

This is what you need to pay attention to. 这是你需要注意的。

Suppose you have a vector 假设你有一个向量

0 1 2 3 4 5 6

and you want to remove the 3. You can turn this into 并且您想要删除3.您可以将其转换为

0 1 2 6 4 5

in O(1) without any issues. 在O(1)没有任何问题。

Actually, there is a way to do it. 实际上,有一种方法可以做到这一点。 Here is the pseudocode: 这是伪代码:

  1. If the element you are trying to remove is the last element in the vector, remove it, done. 如果您要删除的元素是向量中的最后一个元素,请将其删除,完成。
  2. Read the last element of the vector and write it over the element-to-be-removed. 读取向量的最后一个元素,并将其写入要删除的元素。
  3. Remove the last element of the vector. 删除向量的最后一个元素。

You can swap and pop_back in constant time. 你可以在恒定的时间内swappop_back

std::swap(vec.back(), vec[rank]);
vec.pop_back();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM