【问题标题】:Find unique numbers from series without breaking order在不破坏顺序的情况下从系列中查找唯一编号
【发布时间】:2015-04-07 11:16:36
【问题描述】:

我是 stackOverflow 的新手。如果重复发帖,请帮助我。 我是 C++/STL 开发人员,正在寻找:

在不改变其顺序的情况下从整数系列中查找唯一数字。例如:i/p: 10,4,3,6,1,0,4,4,4,10,5,9,0,6,15,.... o/p(预期结果): 10, 4,3,6,1,0,5,9,15,....

约束:- 时间复杂度不应该是最差的(N^2)。需要在更短的时间内解决它。 - 内存充足。 - appricieate,如果你能解释一下我必须用来解决这个问题的 STL 容器或算法。

我尝试使用 unorder_set,但它破坏了排序,所以有点混乱。

【问题讨论】:

  • 你能展示你尝试过的算法吗?
  • O(N) 内存:复制、排序、唯一
  • 最适合cs.stackexchange.com的问题
  • 天真的方法是O(n²),(仅在不存在时插入)。
  • 我不是在寻找幼稚的方法。

标签: c++ algorithm stl


【解决方案1】:

您可以使用std::unique,然后添加resize 来调整vector(或其他容器)的大小:

auto it = myvector.begin();
it = unique (myvector.begin(), myvector.end());                                                                
myvector.resize(distance(myvector.begin(),it) );

【讨论】:

  • 这仅在值已排序时才有效,情况并非如此
  • @VVG - 我怀疑它会维持秩序。你能解释一下它是如何工作的吗?甚至不确定唯一性和调整大小和距离的时间复杂度。请同时提及。
  • @VGG:时间复杂度:排序:O(n log n);独特的:O(n);距离:O(1);调整大小:O(n)......但话又说回来,这是你应该能够自己研究的东西,比如......谷歌
【解决方案2】:

你可以使用 std::unordered_map:

#include <iostream>
#include <vector>
#include <unordered_map>

int main() {
 std::unordered_map<int, int> mynums;
 std::vector<int> myvect = {10,4,3,6,1,0,4,4,4,10,5,9,0,6,15};
 for (auto myelem: myvect) {
   mynums[myelem]++;
 }
 for (auto myelem: mynums) {
   if (myelem.second > 1) {
     std::cout << "Value "<<myelem.first << " " << myelem.second << " times" <<std::endl;
   }
 }
 return 0;
}

该方法仅打印重复的数字,并且应该具有摊销 O(n) 复杂度。

您感兴趣的代码如下所示:

#include <iostream>
#include <vector>
#include <unordered_map>

int main() {
 std::unordered_map<int, int> mynums;
 std::vector<int> myvect = {10,4,3,6,1,0,4,4,4,10,5,9,0,6,15};
 for (auto myelem: myvect) {
   if (mynums[myelem] == 0) {
      std::cout << myelem << ",";
   }
   mynums[myelem]++;
 }

 return 0;
}

【讨论】:

  • 谢谢。我认为我们可以在两个循环中加入俱乐部。 1. 可以线性遍历向量和一个循环 2. 调用 unorder_set::find(myelem)。如果不。找到然后忽略 3. 否则将 myelem 存储在 unordered_set 这将以 O(nlogn) 复杂性完成这项工作,但在一个循环内。在您的逻辑中,它将遍历循环两次,尽管您的情况下的复杂性看起来更好 O(n)。你说什么?
  • 是的,因为插入和访问 unordered_map 的时间是摊销 O(1),所以它会摊销 O(n)。
【解决方案3】:

O(n²) 中的幼稚做法:

std::vector<int> find_unique_numbers(const std::vector<int>& v)
{
    std::vector<int> res;

    for (auto e : v) {
        if (std::find(res.begin(), res.end(), e) == res.end()) {
            res.push_back(e);
        }
    }
    return res;
}

Live demo

【讨论】:

    猜你喜欢
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多