在 int\[\] 数组中找到最受欢迎的元素

新手上路,请多包涵
int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};

我怎样才能写一个方法并返回 7?

我想在没有列表、地图或其他助手的帮助下保持原生。只有数组[]。

原文由 SexyMF 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 277
2 个回答
public int getPopularElement(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;
}

原文由 nIcE cOw 发布,翻译遵循 CC BY-SA 3.0 许可协议

试试这个答案。一、数据:

 int[] a = {1,2,3,4,5,6,7,7,7,7};

在这里,我们构建了一个地图来计算每个数字出现的次数:

 Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : a) {
    Integer count = map.get(i);
    map.put(i, count != null ? count+1 : 1);
}

现在,我们找到频率最高的数字并将其返回:

 Integer popular = Collections.max(map.entrySet(),
    new Comparator<Map.Entry<Integer, Integer>>() {
    @Override
    public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
        return o1.getValue().compareTo(o2.getValue());
    }
}).getKey();

如您所见,最受欢迎的数字是七:

 System.out.println(popular);
> 7

编辑

这是我的答案 ,不 使用地图、列表等,只使用数组;尽管我正在对数组进行就地排序。它的复杂度为 O(n log n),优于 O(n^2) 公认的解决方案。

 public int findPopular(int[] a) {

    if (a == null || a.length == 0)
        return 0;

    Arrays.sort(a);

    int previous = a[0];
    int popular = a[0];
    int count = 1;
    int maxCount = 1;

    for (int i = 1; i < a.length; i++) {
        if (a[i] == previous)
            count++;
        else {
            if (count > maxCount) {
                popular = a[i-1];
                maxCount = count;
            }
            previous = a[i];
            count = 1;
        }
    }

    return count > maxCount ? a[a.length-1] : popular;

}

原文由 Óscar López 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题