如何解决C ++中未排序数组中缺少元素
任何人都可以向我解释 STL C++ 中这种无序集合的逻辑,因为我是这个概念的新手。
他们如何使用无序集合打印数组中缺失的元素。
这种方法是否有效,或者还有其他方法比这种方法有效。
逻辑如下:
for (int x = low; x <= high; x++)
if (s.find(x) == s.end())
cout << x << " ";
完整代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include <unordered_set>
using namespace std;
void printMissing(int arr[],int n,int low,int high)
{
unordered_set<int> s;
for (int i = 0; i < n; i++)
s.insert(arr[i]);
// Traverse throught the range an print all
// missing elements
for (int x = low; x <= high; x++)
if (s.find(x) == s.end())
cout << x << " ";
}
int main()
{
int arr[] = { 1,3,5,4,2,8,7 };
int n = sizeof(arr) / sizeof(arr[0]);
int low = 1,high = 10;
printMissing(arr,n,low,high);
return 0;
}
解决方法
在一般情况下,这可能是最有效的方法。
对于 unordered_set
和 insert
,find
平均具有 恒定时间 复杂度,因此您可以快速存储之前见过的元素第一个 for 循环,然后遍历整个范围并快速检查您是否看过它们。
作为恒定时间复杂度含义的示例,让我们展示一个不具有恒定时间复杂度的示例:
// Traverse throught the range an print all
// missing elements
for (int x = low; x <= high; x++) {
bool found = false;
for (int i = 0; i < n; ++i) {
// if one of the elements in the array matches this x we can
// break out since the element does exist in arr
if (arr[i] == x) {
found = true;
break;
}
}
// was the element found? If not print it out
if (!found) cout << x << " ";
}
对于 low,high
范围内的每个元素,如果元素不存在,我们必须遍历 full 数组(对于大型输入数组,这可能会非常慢)。为 low,high
范围内的单个元素运行此算法所需的时间与数组中的元素数量成线性比例,因此我们称之为线性查找时间。
当数组相对较大时,恒定查找时间通常会超过线性查找时间。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。