這個問題問的人比較多比較高,Examda提示:是寫一個程序判斷一個數(shù)組中出現(xiàn)次數(shù)最多的那個元素。
給出的代碼是:
import java.util.*;
public class FindMostEle {
private static HashMap map;
public static HashMap mostEle(String[] strArray){
map = new HashMap();
String str = "";
int count = 0;
int result = 0;
for(int i=0; i str += strArray[i];
for(int i=0; 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 result = mostEle(strArray);
ArrayList c = new ArrayList(result.values());
Set s = result.keySet();
System.out.print("一共有"+ result.size() +"元素最多。它們分別是");
System.out.print(s);
System.out.println(",分別出現(xiàn)了"+ c.get(0) +"次。");
}
}
結(jié)果是:
一共有3元素最多。它們分別是[2, 11, 4],分別出現(xiàn)了2次。
給出的代碼是:
import java.util.*;
public class FindMostEle {
private static HashMap
public static HashMap
map = new HashMap
String str = "";
int count = 0;
int result = 0;
for(int i=0; i
for(int i=0; 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
ArrayList
Set
System.out.print("一共有"+ result.size() +"元素最多。它們分別是");
System.out.print(s);
System.out.println(",分別出現(xiàn)了"+ c.get(0) +"次。");
}
}
結(jié)果是:
一共有3元素最多。它們分別是[2, 11, 4],分別出現(xiàn)了2次。

