leet-code-4

數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。 

package com.example.study;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 *author:bingbing
 *日期:2020年7月4日
 *時間:下午3:12:46
 *數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。
 */

public class demo03 {
	
	
	public static void main(String[] args) {
		
	   int a[]=new int[] {1, 2, 3, 2, 2, 2, 5, 4, 2};
	   Map<Integer,Integer>  countMap=new HashMap<Integer,Integer>();
	   int count=0;
	   System.out.println(Arrays.toString(a));
	   for(int i=0;i<a.length;i++) {  
		   if(countMap.containsKey(a[i])) {
			   countMap.put(a[i], countMap.get(a[i])+1);
		   }else {
			   countMap.put(a[i], count+1);
		   }
	   }
	   
	   //找出map中key對應的value的值大於數組長度一半的值。
	   int length=a.length/2;
	   for(Object key:countMap.keySet()) {
		   if(countMap.get(key)>length) {
			   System.out.println("該數字爲:"+key);
		   }
	   }
	   
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章