现在的位置: 首页 > 综合 > 正文

判断一个数组中出现次数最多的元素

2013年02月19日 ⁄ 综合 ⁄ 共 1444字 ⁄ 字号 评论关闭

这个问题在CSDN上的上镜率比较高,就是写一个程序判断一个数组中出现次数最多的那个元素。我给出的代码是:

  1. import java.util.*;
  2. public class FindMostEle {
  3.     private static LinkedHashMap<String, Integer> map;
  4.     
  5.     public static LinkedHashMap<String, Integer> mostEle(String[] strArray){
  6.         map = new LinkedHashMap<String, Integer>();
  7.         
  8.         String str = "";
  9.         int count = 0;
  10.         int result = 0;
  11.         
  12.         for(int i=0; i<strArray.length; i++)
  13.             str += strArray[i];
  14.         
  15.         for(int i=0; i<strArray.length; i++){
  16.             String temp = str.replaceAll(strArray[i], "");
  17.             count = (str.length() - temp.length())/strArray[i].length();
  18.             
  19.             if (count > result){
  20.                 map.clear();
  21.                 map.put(strArray[i], count);
  22.                 result = count;
  23.             }
  24.             else if(null == map.get(strArray[i]) && count == result)
  25.                 map.put(strArray[i], count);
  26.         }       
  27.         return map;
  28.     }
  29.     
  30.     public static void main(String args[]){
  31.         String[] strArray = {"11""11""2""2""4""5""4"};
  32.         
  33.         LinkedHashMap<String, Integer> result = mostEle(strArray);
  34.         
  35.         ArrayList<Integer> c = new ArrayList<Integer>(result.values());
  36.         Set<String> s = result.keySet();
  37.         
  38.         System.out.print("一共有"+ result.size() +"元素最多。它们分别是");
  39.         System.out.print(s);
  40.         System.out.println(",分别出现了"+ c.get(0) +"次。");
  41.         
  42.     }
  43. }

结果是:

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

抱歉!评论已关闭.