c++ - 在 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);
}
感谢任何有用的建议,谢谢
解决方案
我认为不需要你的比较,插入为你做: https ://en.cppreference.com/w/cpp/container/set/insert
返回一对由插入元素(或阻止插入的元素)的迭代器和如果插入发生则设置为 true 的 bool 值组成。
只需插入元素并检查插入函数返回的内容(如果重复,则对的第二个元素为 false):)
推荐阅读
- flutter - 颤振将 sharedPrefrence 的值添加到列表
- c# - 在将 DateTime 与 IConfiguration 绑定时使用 DateTimeStyles.RoundtripKind
- jquery - 将焦点从索引转移到活动选项卡的正文并聚焦第一个链接
- vector - 在p5中查找向量与点对点之间的差异
- java - 执行 GET 请求时出现 302 错误
- html - 使内容固定在图像的某个位置附近的前端方法
- css - 子网格布局的问题不是 100% 高度
- firebase - 如何在 Firebase 测试实验室中执行网络 oauth 登录?
- c# - 在 C# 连接字符串中用于 localhost 数据源的内容
- python - 如何根据python中的最大值设置子图的最小和最大限制?