O(N) Simple solution using Map


  • 0
    M
    public class Solution {
        public int majorityElement(int[] nums) {
            
            Map<Integer, Integer> m = new HashMap<>();
            
            for (int num: nums){
                if(m.containsKey(num))
                    m.put(num, m.get(num)+1);
                else
                    m.put(num, 1);
            }
            int thresh = nums.length/2;
            for(int num: nums){
                if(m.get(num)>thresh)
                    return num;
            }
            
            return 0;
            
        }
    }
    

Log in to reply
 

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