首页 > 解决方案 > 数组中最大的非重复元素

问题描述

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

#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];
  }

}

标签: c++

解决方案


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

类似的东西?

#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

推荐阅读