首页 > 解决方案 > 在 C++ 中使用 Set 查找数组中的重复项

问题描述

我目前正在练习编码面试,并且正在研究一个函数,该函数接收一个数组和该数组的大小并打印出其中哪些数字是重复的。我已经使用两个 for 循环方法让它工作,但想要一个使用集合的优化解决方案。我的代码片段如下,

#include <iostream>
#include <set>
using namespace std;

void FindDuplicate(int integers[], int n){
  set<int>setInt;

  for(int i = 0; i < n; i++){

    //if this num is not in the set then it is not a duplicate
    
    if(setInt.find(integers[i]) != setInt.end()){
      setInt.insert({integers[i]});
    }
    else
      cout << integers[i] << " is a duplicate";
  }
}

int main() {
  
int integers [] = {1,2,2,3,3};

int n = sizeof(integers)/sizeof(integers[0]);

FindDuplicate(integers, n);
}

感谢任何有用的建议,谢谢

标签: c++

解决方案


我认为不需要你的比较,插入为你做: https ://en.cppreference.com/w/cpp/container/set/insert

返回一对由插入元素(或阻止插入的元素)的迭代器和如果插入发生则设置为 true 的 bool 值组成。

只需插入元素并检查插入函数返回的内容(如果重复,则对的第二个元素为 false):)


推荐阅读