Majority Element(no 169)

Given an array of size n, find the majority element. The majority element is the element that appears more than⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


import java.util.HashMap;
public class Solution {
    public  int majorityElement(int[] num) {
	        
	        HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
	        for(int i=0;i<num.length;i++){
	           
	            hm.put(num[i],hm.containsKey(num[i])?hm.get(num[i])+1:1);
	            
	        }
	        
	        System.out.println(hm.entrySet());
	        int x=0,tag=0;
	        for(Integer kk:hm.keySet()){	        	      
	        	if(hm.get(kk)>x){
	        		x=hm.get(kk);
	        		tag=kk;
	        	}
	        }
	        
	       return tag; 
	    }
	
}

其中那個foreach循環可以使用迭代器iterator()實現

for(Iterator itr = hm.keySet().iterator(); itr.hasNext();){
			  		   int key = (Integer) itr.next(); 
			  		   if(hm.get(key)>x){
			  			  x=hm.get(kk);
                                                  tag=kk;;			  			   
			  		   }
		   }


發佈了27 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章