在网上看到一个百度的算法题,如题,在一个数组中,找出出现次数最多且数值最大的一个数并输出。上次看视频的时候,突然想到可以通过map集合来做这题,将数值作为键存入map集合,而将出现的次数作为值存入map集合中。然后可以取出元素及元素出现的个数,那么请问各位怎么进行比较呢?取出那个出现次数最多且数值最大的元素。下面是我的代码,求高手指点一下啊。谢谢。
- package test;
- import java.util.*;
- /*查找一个数组中出现次数最多且最大的数。
- * int[] a={1,2,3,2,4,2,4,2}
- * */
- public class FindArray {
- public static void main(String[] args) {
- int[] in ={2,4,3,2,4,2,3};
- findElement(in);
- }
- public static void findElement(int[] in){
- Map<Integer,Integer> map =new TreeMap<Integer,Integer>();
- for(int x = 0;x<in.length;x++){
- Integer value = map.get(in[x]);
- if(value==null){
- map.put(in[x],1);
- }
- else
- map.put(in[x], ++value);
- }
- Set<Integer> set = map.keySet();
- Iterator<Integer> iterator = set.iterator();
- while(iterator.hasNext()){
- Integer key = iterator.next();
- int count = map.get(key);
- System.out.println(key+"出现了"+count+"次");
- }
- }
- }
|
|