My java solution


  • 0
    C
    public class Solution {
    public int majorityElement(int[] nums) {
        //define a map to store the occur time of each element
    	HashMap<Integer, Integer> map = new HashMap();
    	int length = nums.length;
    	
    	if(length == 1) return nums[0];
    	
    	for(int i=0;i<length;i++)
    	{
    		//fst time occur in the array
    		if(map.get(nums[i]) == null)
    		{
    			map.put(nums[i], 1);
    		}
    		//already in the map
    		else
    		{
    			Integer currentValue = map.get(nums[i]);
    			currentValue++;
    			if(currentValue>length/2)
    				return nums[i];
    			map.put(nums[i], currentValue);
    		}
    	}
    	return 0;
    }
    

    }


Log in to reply
 

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