数组中最大的非重复元素

时间:2018-10-31 18:11:16

标签: c++

所以我需要编写程序,计算给定数组中最大的非重复元素。目前,我编写了计算最大数组的程序,但无法编写对新数组中的非重复元素进行排序的算法。我的代码:

#include <iostream>
#include <iomanip>
#include <algorithm>

using namespace std;
int main()
{
int n,a[20],b[20],did=0;
cin >> n;
for(int i=0;i<n;i++)
 {
  cin >> a[i]; // reading input 
 }
for(int i=0;i<n;i++) // biggest
 {
  did=a[0];
   if(did<a[i])
   did=a[i];
 }
for(int i=0;i<n;i++) // trying to write non repetitive ones in new array
  {
   for(int j=i+1;j<n;j++)
    {
     if(a[i]!=a[j])
     b[i]=a[j];
    }
  }
for(int i=0;i<n;i++) // biggest from non-repetitive array
  {
   if(b[i]>b[i-1] && b[i]>b[i+1] && b[i]==did)
   cout << b[i];
  }

}

1 个答案:

答案 0 :(得分:0)

(我假设数组不为空,并且也具有非重复的正值)

类似的东西吗?

#include <vector>
#include <map>

int main()
{
    std::map<int, int> m;

    // The "array":
    std::vector<int> ar{3, 3, 4, 6, 7, 800, 123, 245, 245, 700, 800, 800};

    // Count number of repetitions for each element: 
    for (auto el : ar)
        m[el]++;

    // Extract the biggest that has only one appearance:
    int result = 0;
    for (auto iter = m.rbegin(); iter != m.rend(); ++iter) {
        if (iter->second == 1) {
            result = iter->first;
            break;
        }
    }

    return result; // 700 in this example
}

如果您坚持使用C数组(也可以使用std :: array):

std::map<int, int> m;

// The array:
const size_t ARRAY_SIZE = 13;
int ar[ARRAY_SIZE] { 3, 3, 4, 5, 6, 7, 800, 123, 245, 245, 700, 800, 800 };

// Count number of repetitions for each element: 
for (size_t i = 0; i < ARRAY_SIZE; i++)
    m[ar[i]]++;

// From here is the same code as in the std::vector use example