300分！给一个数组 求里面出现次数最多的元素和其次数 另：需要加上时间复杂度，否则只给5分。最优算法给100分,该怎么处理(4)

www.MyException.Cn  网友分享于：2013-01-16  浏览：81次

------解决方案--------------------

import java.util.*;
public class Test1{
public static void main(String args[]){
String[] s = {"a","b","a","a","b","c"};
HashMap< String, Integer> hm = new HashMap< String, Integer>();

for (int i = 0; i < s.length; i++) {
if (!hm.containsKey(s[i])) {
hm.put(s[i], 1);
} else {
hm.put(s[i], hm.get(s[i]).intValue()+1);
}
}

System.out.println(hm);
}
}

{a=3, c=1, b=2}

import java.util.*;
public class FindMostEle {

public static LinkedHashMap<String, Integer> mostEle(String[] strArray){

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(null == map.get(strArray[i]) && count == result)
map.put(strArray[i], count);
}
return map;
}

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

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) +"次。");

}
}

import java.util.*;
public class test {
public static void main(String[] args) {
int[] array = {1,2,2,3,4,4,5,6,7,7,8,9};
int iMaxCount=0;
//因为可能有多个元素的出现次数同时位居第一，
//所以结果应该是一个集合。用一个List来装载。
List< Integer> list=new ArrayList< Integer>();
for (int i=0;i< array.length;i++){
int iCount=0;
for (int j=0;j< array.length;j++){
if (array[i]==array[j])
iCount++;
}
if (iCount>iMaxCount){
list.clear();
iMaxCount=iCount;
}else if (iCount==iMaxCount){
if (list.indexOf(array[i])==-1)