c++ - 找到具有最少重复次数的最小元素

标签 c++ arrays algorithm

程序获取数组的大小和数组元素作为输入。并且程序应该打印此数组中重复次数最少的最小元素。

数组的大小是从1100

数字范围从1100

例如,如果输入是[1,2,1,3,4],则输出必须是2

我试图找出每个数组元素的重复次数,然后以某种方式将它与原始问题联系起来,但我找不到方法。

非常感谢您抽出宝贵时间并提前提供帮助。

最佳答案

int main ()
{
  // array input 
  int ar[] = { 1, 1, 2, 2, 2, 3, 3, 3, 3, 5, 6, 6, 6 };
  size_t n = sizeof (ar) / sizeof (ar[0]);

  // since maximun size of the array element is 100
  int occurrence[101];

  // set occurrence to zero 
  memset (occurrence, 0, sizeof occurrence);

  for (int i = 0; i < n; i++)
    {
      // count the occurrence of each number
      occurrence[ar[i]]++;
    }

  // let's set minValue to INT_MAX
  int minValue = INT_MAX, Value;

  // since the number range is 1 to 100
  for (int i = 1; i <= 100; i++)
    {
      // Update minValue and Value
      if (occurrence[i] != 0 and occurrence[i] < minValue)
        {
             minValue = occurrence[i];
            Value = i;
        }
    }

  // print the result 
  printf ("%d", Value);
  return 0;
}

输出:

5

关于c++ - 找到具有最少重复次数的最小元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57899646/

相关文章:

.net - 是否有任何模式或实践可以在 .NET 中以非侵入式方式将调试/日志代码引入现有算法?

c++ - 为共享指针C++单独实例化一个对象

c++ - 如果将 a 类实例声明为 A a,那么 a 类实例将位于内存中的哪个位置?

javascript - AngularJS - 如何将键值对插入数组?

根据观察到的日出计算二维地形的算法

c++ - 所有可能的游戏分数的总和

c++ - 为每个参数选择调用一次的静态变量和函数

c++ - 丢弃 volatile 安全吗?

C++。每帧更新和复制一系列值。我应该使用哪种类类型?

php - 将数组存储到数据库php