A solution using java Map


  • -4
    M

    public class Solution {
    public List<Integer> majorityElement(int[] nums) {

     List<Integer> list = new ArrayList<Integer>();
    	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/3)){
    	    	
    	    	
    	    list.add(entry.getKey());
    	    	
    	    	
    	    	
    	    }
    	  
    	}  
    	
    	return list;
    }
    

    }


  • 0
    E

    At least you don't fit into memory limits. You are using additional 2 sizeof(Integer) * n * (memory used for internal data in HashMap, depends on implementation)*


Log in to reply
 

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