如何找出数组中重复元素最多的数

package java程序员面试笔试宝典;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class 题8_5_4数组中重复元素最多的数 {
	public static void main(String[] args) {
		int[] a={1,1,1,2,2,4,4,4,4,5,5,6,6,6,6,6};
		System.out.println(getMostFrequentArray_0(a));
		
	}
	//空间换时间
	public static int getMostFrequentArray_1(int[] a){
		int[] count=new int[a.length];
		int max=0;
		for (int i = 0; i < count.length; i++) {
			count[a[i]]++;
			if(count[a[i]]>max){
				max=count[a[i]];
			}
		}
		return max;
	}
	//map映射表
	public static char getMostFrequentArray_0(int[] a){
		Map map=new TreeMap();
		for (int i = 0; i < a.length; i++) {
			if(map.containsKey(a[i])){
				map.put(a[i], map.get(a[i])+1);
			}else {
				map.put(a[i], 1);
			}
		}
		Object[] m=map.entrySet().toArray();
		String str=new String(m[m.length-1]+"");
		char max=str.charAt(2);
		return max;
	}
	public static int getMostFrequentArray(int[] a){
		int curNumber=a[0];
		int count=0;
		int max=0;
		for (int i = 0; i < a.length; i++) {
			if(curNumber==a[i]){
				count++;
			}else {
				if(count>max){
					max=count;
				}
				count=1;
				curNumber=a[i];
			}
			
			if(i==a.length-1&&count>max){
				max=count;
			}
		}
		return max;
	}
}

 

你可能感兴趣的:(程序员面试笔试宝典)