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

题目描述:

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

思路:

使用Map映射表记录每一个元素出现的次数,然后判断次数大小,进而找出重复次数最多的元素。key表示数组的元素,value表示这个元素在数组中出现的次数。最后对map进行遍历。

代码:

/** 
	 * 使用map(不允许重复的),key是a中元素的值,value是元素出现的次数
	 * @param a
	 * @return
	 */
	private int findMostFrequentInArray(int[] a) {
		Map<Integer, Integer> map = new HashMap<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);
			}
		}
		int index=0;//数组中重复元素最多的数
		int val = 0;//最多的次数
		Iterator<Entry<Integer, Integer>> iterator = map.entrySet().iterator();
		while(iterator.hasNext()){
			Entry<Integer, Integer> next = iterator.next();
			int key = next.getKey();
			int value = next.getValue();
			if(value > val){
				index = key;
				val = value;
			}
		}
		return index;
	}

测试代码:

@Test
	public void test1(){
		int[] a = {1,1,1,1,1,2,2,4,4,4,4,5,5,6,6,6};
		System.out.println(findMostFrequentInArray(a));
	}

猜你喜欢

转载自blog.csdn.net/weixin_38108266/article/details/81272830