【问题标题】:Checking for duplicates in an array using for loop使用 for 循环检查数组中的重复项
【发布时间】:2020-11-01 04:23:40
【问题描述】:

我正在尝试检查用户输入数组中是否有任何重复的整数。问题是副本的验证无法正常工作,我不知道为什么它没有显示所需的输出。以下是代码:

#include <iostream>

using namespace std;

int main()
{
    int length;
    int arrValue;

    cout << "Enter the length : ";
    cin >> length;

    int *arr = new int[length];

    cout << "Enter " << length << " integers for array : ";

    for(int i = 0; i < length; i++)
    {
        cin >> arr[i];
    }

    cout << "Array : ";

    for(int i = 0; i < length; i++)
    {
        arrValue = arr[i];
    
        for(int k = i + 1; k < length; k++)
        {
            if(arr[i] == arr[k])
            {
                cout << "Duplicate found" << endl;
                break;
            }
            else
            {
                cout << arrValue << " ";
            }
        }
    }

   delete[] arr;
}

当前结果(假设用户输入没有重复):

Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 5 5 5 4 4 4 3 3 2

预期结果(假设用户输入没有重复):

Enter the length: 5
Enter 5 integers for array : 5 4 3 2 1
Array : 5 4 3 2 1

当前结果(假设用户输入重复):

Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : 5 5 5 5 Duplicate found 4 4 3

预期结果(假设用户输入重复):

Enter the length: 5
Enter 5 integers for array : 5 4 4 2 1
Array : Duplicate found

我相信我的循环是问题的根源。当前结果输出了10次,我不明白为什么会出现这么多相同的数字。

请注意,我尝试仅使用循环而不是 C++ 标准库来应用验证。

【问题讨论】:

    标签: c++ arrays c++11


    【解决方案1】:

    您的代码中的问题是您打印出每个数组元素每次一个特定元素不匹配另一个元素。您似乎只想打印出是否找到 any 重复值。为此,您可以使用bool 标志来指示是否有任何元素重复:

    bool found_dup = false;
    for(int i = 0; i < length; i++)
        for(int k = i + 1; k < length; k++)
            if(arr[i] == arr[k])
            {
                 found_dup = true;
                 break;
            }
            //  else: don't print anything yet
    

    然后在最后打印出数组:

    if (found_dup)
        std::cout << "Duplicate found";
    else
        for(int i = 0; i < length; i++)
            std::cout << arr[i] << " ";
    

    【讨论】:

    • 谢谢。我想用 bool 创建另一个验证,这与我正在寻找的最接近。 :)
    【解决方案2】:

    您可以以更增强的方式实现程序(您不需要手动定义长度 - 请注意代码中以 cmets 给出的解释):

    #include <iostream>    // for input/output operation
    #include <vector>      // for dynamic array management
    #include <sstream>     // to split the user inputs and assign them to the vector
    #include <algorithm>   // to sort the vector
    #include <string>      // to work with getline()
    
    // using this statement isn't recommended, but for sake of simplicity
    // and avoiding the use of std:: everywhere temporarily (for small programs)
    using namespace std;
    
    int main(void) {
        vector<int> numbers;
        vector<int> duplicates;
        string input;
        int temp;
    
        // getting the user input as string
        cout << "Enter the numbers: ";
        getline(cin, input);
    
        stringstream ss(input);
    
        // splitting the user input string into integers and assigning
        // them into the vector
        while (ss >> temp)
            numbers.push_back(temp);
    
        // sorting the vector in increasing order
        sort(numbers.begin(), numbers.end());
    
        // getting the unique numbers (which are not repeated)
        cout << "Unique numbers: ";
    
        for (size_t i = 0, len = numbers.size(); i < len; i++) {
            if (temp == numbers[i])
                // if found a duplicate, then push into the 'duplicates' vector
                duplicates.push_back(temp);
            else
                cout << numbers[i] << ' ';
    
            temp = numbers[i];
        }
    
        // getting the duplicates
        cout << "Total duplicates: ";
        for (size_t i = 0, len = duplicates.size(); i < len; i++)
            cout << duplicates[i] << ' ';
        cout << endl;
    
        return 0;
    }
    

    它会输出如下内容:

    Enter the numbers: 1 4 8 9 3 2 3 3 2 1 4 8
    Unique numbers: 1 2 3 4 8 9 
    Total duplicates: 1 2 3 3 4 8
    

    【讨论】:

      【解决方案3】:

      请把 if 条件改成这样。

      cout << "Enter the length : ";
          cin >> length;
      
          int *arr = new int[length];
      
          cout << "Enter " << length << " integers for array : ";
      
          for(int i = 0; i < length; i++)
          {
              cin >> arr[i];
          }
      
          cout << "Array : ";
      
          for(int i = 0; i < length; i++)
          {
              arrValue = arr[i];
          
              for(int k = i + 1; k < length; k++)
              {
                  if(arrValue == arr[k])             //change here.
                  {
                      cout << "Duplicate found" << endl;
                      break;
                  }
                  else
                  {
                      cout << arrValue << " ";
                  }
              }
          }
      
         delete[] arr;
      }
      

      我还建议使用地图数据结构。 Map 允许您计算数字的频率,从而在线性时间内检测重复。

      map<int, int> m; // specify the key-value data-type.
      
      for(int i = 0;i<length;i++)
      {
           m[arr[i]]++;
      }
      
      map<int, int>::iterator it; // an iterator to iterate over the datastructure.
      for(it = m.begin();it!=m.end();it++)
      {
           if(it->second>1)             //it->second refers to the value(here, count).
           {
                cout<<it->first<<" ";   //it->first refers to the key.
           }
      }
      

      【讨论】:

        【解决方案4】:

        您的循环实际上为第一个元素迭代 n-1 次,为第二个元素迭代 n-2 次等,其中 n 是数组的长度。这就是为什么对于 5 元素数组,您已经打印了 5 4 次。

        但一般来说,如果目的是检测数组中的重复项,那么这种策略并不是最好的。请注意,具有示例数组4 3 4,使用当前方法,您将正确检测到第一个4,第三个元素也是4,但是一旦您移动到第三个元素,它将被标记为正常,因为它不检查第一个元素。

        您可以考虑另一种策略:创建另一个 n 大小的数组。然后遍历您的原始数组并为每个元素检查该元素是否已经在新数组中。如果您检测到存在,您可能会引发duplicate 事件。否则,您可以将此元素添加到数组中。

        【讨论】:

          【解决方案5】:

          它不起作用,因为您每次找到不同的值时都试图打印相同的值。我在这里得到了一个解决方案,其中包含一个存储数组的数组。它也适用于一个数组。

          #include <iostream>
          
          using namespace std;
          
          int main()
          {
              int length;
              int arrValue;
          
              cout << "Enter the length : ";
              cin >> length;
          
              int *arr = new int[length];
              int *noDuplicateArr = new int[length];
          
              cout << "Enter " << length << " integers for array : ";
          
              for(int i = 0; i < length; i++)
                  cin >> arr[i];
          
              cout << "Array : ";
          
              bool duplicateFound = false;
              int noDuplicateArrLen = 0;
          
              for(int i = 0; i < length && !duplicateFound; i++)
              {
                  arrValue = arr[i];
          
                  int k;
          
                  for(k = i + 1; k < length; k++)
                  {
                      if(arrValue == arr[k])
                      {
                          duplicateFound = true;
                          break;
                      }
                  }
          
                  if (k == length)
                      noDuplicateArr[noDuplicateArrLen++] = arrValue;
              }
          
              if (duplicateFound)
              {
                  cout << "Duplicate found";
              }
              else
              {
                  for (int i = 0; i < noDuplicateArrLen; i++)
                  {
                      cout << noDuplicateArr[i] << " ";
                  }
              }
          
              delete[] arr;
              delete[] noDuplicateArr;
          }
          

          这是只有一个数组的版本:

          #include <iostream>
          
          using namespace std;
          
          int main()
          {
              int length;
              int arrValue;
          
              cout << "Enter the length : ";
              cin >> length;
          
              int *arr = new int[length];
          
              cout << "Enter " << length << " integers for array : ";
          
              for(int i = 0; i < length; i++)
                  cin >> arr[i];
          
              cout << "Array : ";
          
              bool duplicateFound = false;
              int noDuplicateArrLen = 0;
          
              for(int i = 0; i < length && !duplicateFound; i++)
              {
                  arrValue = arr[i];
          
                  int k;
          
                  for(k = i + 1; k < length; k++)
                  {
                      if(arrValue == arr[k])
                      {
                          duplicateFound = true;
                          break;
                      }
                  }
          
                  if (k == length)
                      arr[noDuplicateArrLen++] = arrValue;
              }
          
              if (duplicateFound)
              {
                  cout << "Duplicate found";
              }
              else
              {
                  for (int i = 0; i < noDuplicateArrLen; i++)
                  {
                      cout << arr[i] << " ";
                  }
              }
          
              delete[] arr;
          }
          

          【讨论】:

            猜你喜欢
            • 2023-03-14
            • 1970-01-01
            • 2014-06-28
            • 1970-01-01
            • 2021-05-07
            • 1970-01-01
            • 2021-05-17
            • 2023-03-27
            相关资源
            最近更新 更多