我自己写了一个,不过做不下去了,感觉自己的方向错了,所以上来问一下高手
这段代码改一下是不是可以实现这个功能,或者有更好的方法/**
 *求出一个数组中出现次数最多的数,如果有多个数出现次数相同,一同列出 
 */
import java.util.TreeMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;class ArrayLookup
{
public void getMaxCount(int[] iArr)
{
int i = 0; //临时变量 
int j = 0; //临时变量
int count = 1; //记录相同数字出现次数
int temp = 0; //记录数组中相同元素的值
int max = 0; //记录出现次数最多的数
//数组排序
Arrays.sort(iArr);
TreeMap<Integer,Integer> tm = new TreeMap<Integer,Integer>();
//将数字与其出现次数存入Map集合
while(i<iArr.length)
{
for(j= i+1; j<iArr.length && iArr[i]==iArr[j]; j++)
count++;
tm.put(iArr[i],count); 
count = 1;
i = j;
}

Set<Map.Entry<Integer,Integer>> set = tm.entrySet();
Iterator<Map.Entry<Integer,Integer>> it = set.iterator();

while(it.hasNext())
{
Map.Entry<Integer,Integer> me = it.next();
System.out.println(me.getKey() + "出现 " + me.getValue() + " 次");
}
}
}
public class ArrayLookupMain { private int count;
    public static void main(String[] args)
    {
     int[] intArray = {2,3,4,2,3,4};//,2,2,2,2,5,2,12,6,8,4,3,7,7,5,3,2,5,8,9,8,8,4,5,4,6,8,9,0,5,3,3,2,4,4,7,8,5,34,5,6,5,3,34,6,7,8,9,0};
     ArrayLookup arr = new ArrayLookup();
     arr.getMaxCount(intArray);  
    }   
}

解决方案 »

  1.   

    要是我写的话,也是对每个进行计数 public static void printMaxCount(int [] array)
    {
    HashMap hm = new HashMap();
    int maxCount = 0;//store max count
    int tempCount = 0;//store temp count for every int in array

    //count every int in array,and put it in a hashmap,key is int value, value is count
    for(int i=0;i<array.length;i++)
    { tempCount = 1;
    if(hm.containsKey(array[i]))//if contains,get it and add it,else its count is 1
    {
    tempCount = (Integer)hm.get(new Integer(array[i]));
    tempCount++;
    }
    if(tempCount > maxCount)//to store max count
    {
    maxCount = tempCount;
    }
    hm.put(array[i], tempCount);
    }

    //print all integers which owns max count
    Set<Map.Entry> set = hm.entrySet();
    for (Map.Entry entry : set) 
    {
    if(entry.getValue().equals(maxCount))
    {
    System.out.println(entry.getKey());
    }
    }
    }
    public static void main(String[] args) throws IOException 

    int [] ttt={1,1,2,2,3,4,5,5};
    printMaxCount(ttt);
    } 输出结果2
    1
    5
      

  2.   

    你的程序也可以,不过你要记录最大的count,不是最大的数
    程序的效率也不高,虽然我的也不高,呵呵
    像array.sort(),两个循环嵌套都不是很好的写法,特别是循环内改变循环变量的值都是不好的写法