My easy java solution


  • -2
    D
    public class Solution {
        public int majorityElement(int[] num) {
            if(num.length == 1) {
    			return num[0];
    		}
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    		int result = -1;
    		int sum = 1;
    		
    		for(int i = 0; i < num.length; i++) {
    			if(map.containsKey(num[i])) {
    				map.put(num[i], map.get(num[i])+1);
    			} else {
    				map.put(num[i], 1);
    			}
    		}
    		
    		for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
    			if(entry.getValue() > sum) {
    				sum = entry.getValue();
    				result = entry.getKey();
    			}
    		}
    		
    		return result;
        }
    }

Log in to reply
 

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