简体   繁体   English

有没有办法在 STRING 数组中找到最常见的元素?

[英]Is there a way to find the most common element in a STRING array?

I have this code below, but it works with integers.我在下面有这段代码,但它适用于整数。 I am wanting to get the same thing working for a string array.我想让同样的东西适用于字符串数组。 In particular if say there were names to a string array like 'char []a = "Sparky", "Mary", "Sparky", "John", "Betsy" ', how to get Sparky selected.特别是如果说字符串数组有名称,例如'char []a = "Sparky"、"Mary"、"Sparky"、"John"、"Betsy"',如何选择 Sparky。

    int[] a
    int count = 1, tempCount;
    int popular = a[0];
    int temp = 0;
    for (int i = 0; i < (a.length - 1); i++)
    {
      temp = a[i];
      tempCount = 0;
      for (int j = 1; j < a.length; j++)
      {
        if (temp == a[j])
          tempCount++;
      }
      if (tempCount > count)
      {
        popular = temp;
        count = tempCount;
      }
    }
    return popular;

A simple way to do this is sort the array (eg using the standard function qsort() ) and then iterate over it, keeping track of:一种简单的方法是对数组进行排序(例如,使用标准 function qsort() )然后对其进行迭代,跟踪:

  1. the most common string you've seen so far,到目前为止你见过的最常见的字符串,
  2. how many times you've seen the most common string,你见过多少次最常见的字符串,
  3. the latest string you've seen,你见过的最新字符串,
  4. how many times you've seen the latest string.你看过多少次最新的字符串。

If (4) exceeds (2), you update (1).如果 (4) 超过 (2),则更新 (1)。

This requires on aeverage O(n log n) time and O(log n) to sort the array and O(n) to scan it as described.这需要平均 O(n log n) 时间和 O(log n) 来对数组进行排序,并且需要 O(n) 来按照描述的方式扫描它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM