从数字数组中删除重复
Removing duplicates from an array of numbers
我正在尝试在C 中编写一个程序,其中我将一系列数字输入a[]
,然后将数字输出到b[]
中,以删除任何重复项。例如,a[] = {1,3,7,6,3,7}
将输出b[] = {1,3,7,6}
。谢谢!
int main() {
int a[10];
int i, n, j;
cout << "n=";
cin >> n;
for (i = 0; i <= n - 1; i++) {
cout << "a[" << i << "]=";
cin >> a[i];
}
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] == a[j]) {
cout << "b= " << a[i] << endl;
}
}
}
for (i = 0; i <= n; i++) {
if (a[i] != a[j]) {
cout << "b=" << a[i] << endl;
}
}
}
如果您想摆脱副本(并保留订单(,则C 的惯用方式是使用std :: set :: set and std :: vector(在此处仅显示相关的smippet为您的示例(:
int a[] = {1,3,7,6,3,7};
std::set<int> c;
std::vector<int> b;
for(auto v: a)
if(c.insert(v).second)
b.push_back(v);
for(auto v: b)
std::cout << v << std::endl;
输出:
1
3
7
6
您的代码应更改为此(数组的顺序在代码片段中都不会尊重(:
for (i = 0; i < n; i++) {
bool notDup = true;
for (j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
notDup = false;
break;
}
}
if(notDup)
cout << "b= " << a[i] << endl;
}
但是,解决问题的解决方案是构建std::set
,它将省略重复项。
vector<int> a{1,3,7,6,3,7};
set<int> b(a.begin(), a.end());
for (auto& elem : b)
{
std::cout<<elem<<'n';
}
live
使用std::unordered_set
跟踪您已经保留的元素。另外,使用std::vector
代替C风格数组。
vector<int> a{1, 3, 7, 6, 3, 7},
b;
unordered_set<int> s;
for(auto i : a)
{
if (s.insert(i).second)
{
b.push_back(i);
}
}
有很多方法可以从向量中删除重复项。
从Oblivion
解决方案中,简单的方法将它们插入集合,然后从集合中获取值。
vector<int> a{1,3,7,6,3,7};
set<int> b(a.begin(), a.end());
for (auto& elem : b)
{
std::cout<<elem<<'n';
}
另一种方法是在STL中使用唯一。如果您不想使用更多的内存,那么此解决方案是完美的。时间复杂性是O(nlogn)
。
vector<int> a{1,3,7,6,3,7};
sort(a.begin(), a.end());
a.erase(unique(a.begin(), a.end()), a.end());
相关文章:
- 如何在 getline 中删除/忽略超过特定数字的字符?
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- C++ 从 std::string 中删除所有非数字字符
- 如何删除文件中的数字,通过 c++ fstream 的
- 删除C++中向量中第一个最小的数字(并保持顺序)
- 我应该如何使用remove_if删除两个数字范围内的元素
- 取代表开始/结束的数字对,并删除重叠
- 如何从数组中删除重复的数字?
- 删除数字并在C++中保留字符串的下划线
- 无法使用"擦除"函数从 c++ 字符串中删除数字
- C++ 使用数字删除文件 io 行
- 代码问题.使用矢量删除相同的数字,除了它的最后一个入口
- 如何删除n个数字中的C数字
- 删除数组中所有出现的数字 C++
- 使用find_if从向量删除所有偶数数字
- 用数字删除文件
- 我不想要最后一个数字/值后面的逗号,如何删除它(c ++,循环)
- 从控制台获取的每 30 秒输入后,从 Vector 中逐个删除数字
- 从堆栈中删除数字
- 删除<数字>在O(n)时间内来自容器的元素的数量