【问题标题】:print duplicate elements in array打印数组中的重复元素
【发布时间】:2021-05-03 16:15:46
【问题描述】:

我想在动态数组中查找重复元素。在大多数情况下它都有效,但它如何适用于这种情况。我在给定的数组中找到重复的元素。但是有一个问题是我的重复元素也可以重复。我该如何解决那部分。

      #include <iostream>

      int main() {
      unsigned n;
      std::cin >> n; 
      int count = 0;
      int* dynArr = new int[n];
      for (int i = 0; i < n; i++) {
          std::cin >> dynArr[i];
      }
      for(int i = 0; i < n; i++){
          for(int j = i + 1; j < n; j++){
               if(dynArr[j] == dynArr[i]){
                   std::cout<<dynArr[j]<<" ";
                   break;
               }
           }
       }
     }

这部分有问题。当我输入我的数组长度为 6 和元素 {1,1,2,1,2,2} 时。 我得到了(1,1,2,2)。 但我只需要得到 1,2。

input 6
      1 1 2 1 2 2
output 1 1 2 2 

但必须是

output 1 2

【问题讨论】:

  • 您需要将重复项记住在一个单独的数组中,并且只存储一次,如果您找到一个新的。完成之后,打印出你记住这些重复的数组。
  • 请注意,一种简单有效的方法是先对数组进行排序。或者使用std::map

标签: c++ arrays dynamic duplicates difference


【解决方案1】:

这是一个简单快速的解决方案。

  std::map<int,size_t> element_count;

  for(int i = 0; i < n; i++){
      if ( ++element_count[dynArr[i]] == 2 ){
               // Only report on the second occurrance
               std::cout<<dynArr[j]<<" ";
       }
   }

【讨论】:

  • ...或者如果集合可能很大,请考虑使用std::unordered_map 而不是std::map
【解决方案2】:
const int listSize = 5;
int list1[listSize] = {0,0,1,1,3};
bool dupList[listSize] = {false};
for (int index = 0; index < listSize; index++) {
    int val = list1[index];
    for (int i = 0; i < listSize; i++) {
        if (i != index) {
            if (list1[i] == val) {
                dupList[index] = true;
            }
        }
    }
}
int printList[listSize];
int addNum = 0;
for (int index = 0; index < listSize; index++) {
    if (dupList[index] == true) {
        bool run = true;
        int print = list1[index];
        for (int i = 0; i < listSize; i++) {
            if (printList[i] == print) {
                run = false;
            }
        }
        if (run == true) {
            std::cout << print << " ";
            printList[addNum] = print;
            addNum++;
        }
    }
}

请注意,此代码根本不会快速运行,仅在操作不需要多次运行时才使用它,但它只会显示重复的单个数字。它肯定需要进一步优化

【讨论】:

  • 输出将是 0 1
【解决方案3】:

您只需使用两个std::set&lt;int&gt;s 即可完成。

#include <set>
#include <iostream>

int main() {
    unsigned n;
    std::cin >> n;
    int count = 0;
    std::set<int> all;
    std::set<int> redundant;

    for (int i = 0; i < n; i++) {
        int input = 0;
        std::cin >> input;

        // You cant enter the entry because its present. This will return a std::pair<,> with the second value false.
        if (!all.insert(input).second)
            redundant.insert(input);    // We store this in another set so we dont duplicate the redundant entries.
    }

    for (auto itr = redundant.begin(); itr != redundant.end(); itr++)
        std::cout << *itr << " ";
}

【讨论】:

    猜你喜欢
    • 2012-06-09
    • 2013-09-12
    • 2017-10-13
    • 1970-01-01
    • 2014-12-08
    • 2012-10-24
    • 2012-05-13
    • 2013-06-21
    • 2012-09-25
    相关资源
    最近更新 更多