A 33ms Solution using java Map!


  • 1
    M

    public class Solution {
    public int majorityElement(int[] nums) {

        int majorelement = 0;
    	Map<Integer,Integer> map = new HashMap<Integer,Integer>();
    	
    	for(int i = 0;i<nums.length;i++){
    		
    		if(null == map.get(nums[i])){
    			
    			
    			map.put(nums[i], 1);
    			
    		}else{
    			
    			map.put(nums[i], map.get(nums[i]) + 1);
    			
    		}
    		
    	}
    	
    	for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
    		  
    	    
    	    if(entry.getValue()>(nums.length/2)){
    	    	
    	    	
    	    	majorelement =   entry.getKey();
    	    	
    	    	
    	    	
    	    }
    	  
    	}  
    	
    	return majorelement;
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.