【问题标题】:Missing elements in unsorted array in C++C ++中未排序数组中缺少元素
【发布时间】:2021-07-08 14:19:34
【问题描述】:

任何人都可以向我解释 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;
}

【问题讨论】:

  • 他们将所有数组元素添加到集合中,然后遍历一个范围并打印不在集合中的数字。您有更具体的问题吗?

标签: c++ arrays c++14 hashtable unordered-set


【解决方案1】:

在一般情况下,这可能是最有效的方法。

unordered_set 对于insertfind 平均具有恒定时间复杂度,因此您可以在第一个 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 范围内的单个元素运行此算法所需的时间与数组中元素的数量成线性关系,因此我们称之为线性查找时间。

当数组比较大时,常数查找时间一般会优于线性查找时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多