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

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<Integer, Integer> map=new TreeMap<Integer, Integer>();
		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;
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值