在 int[] 数组中找到最受欢迎的元素 [英] Find the most popular element in int[] array

查看:44
本文介绍了在 int[] 数组中找到最受欢迎的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何编写方法并返回 7?

how can I write a method and return 7?

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

I want to keep it native without the help of lists, maps or other helpers. Only arrays[].

推荐答案

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

这篇关于在 int[] 数组中找到最受欢迎的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆