AC Java solution using hashmap


  • 1
    F
    public int majorityElement(int[] nums) {
        int res = 0, max = 0;
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])) {map.put(nums[i],map.get(nums[i]) + 1);}
            else {map.put(nums[i],1);}
        }
        for(int i : map.keySet()){
            if(map.get(i) > max){
                max = map.get(i);
                res = i;
            }
        }
        return res;
    }
    

    }


Log in to reply
 

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