专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »Java教程 » 数组元素:找出一个数组中出现次数最多的那个元素 »正文

数组元素:找出一个数组中出现次数最多的那个元素

来源: 发布时间:星期一, 2008年10月20日 浏览:131次 评论:0

这个问题问的人比较多比较高,所以我就是写一个程序判断一个数组中出现次数最多的那个元素。

我给出的代码是:

import java.util.*;

public class FindMostEle {
private static HashMap<String, Integer> map;

public static HashMap<String, Integer> mostEle(String[] strArray){
map = new HashMap<String, Integer>();

String str = "";

int count = 0;
int result = 0;

for(int i=0; i<strArray.length; i++)
str += strArray[i];

for(int i=0; i<strArray.length; i++){
String temp = str.replaceAll(strArray[i], "");
count = (str.length() - temp.length())/strArray[i].length();

if (count > result){
map.clear();
map.put(strArray[i], count);
result = count;
}
else if(count == result)
map.put(strArray[i], count);
}
return map;
}

public static void main(String args[]){
String[] strArray = {"11", "11", "2", "2", "4", "5", "4"};

HashMap<String, Integer> result = mostEle(strArray);

ArrayList<Integer> c = new ArrayList<Integer>(result.values());
Set<String> s = result.keySet();

System.out.print("一共有"+ result.size() +"元素最多。它们分别是");
System.out.print(s);
System.out.println(",分别出现了"+ c.get(0) +"次。");

}
}
结果是:

一共有3元素最多。它们分别是[2, 11, 4],分别出现了2次。

0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: