Java solution in HashMap


  • 0
    T

    public class Solution {
    public int majorityElement(int[] nums) {
    int half = nums.length /2;
    HashMap map =new HashMap();
    for(int i= 0;i<nums.length;i++){
    int key = nums[i];
    if(map.containsKey(key)){
    map.put(key,(int)map.get(key) + 1);
    }else{
    map.put(key,1);
    }
    }

        Iterator it = map.keySet().iterator();
        int max = 0;
        int maxKey = 0;
        while(it.hasNext()){
            int key = (int)it.next();
            int val = (int)map.get(key);
            if(val >= half && val > max){
                max = val;
                maxKey = key;
            }
        }
        return maxKey;
    }
    

    }


Log in to reply
 

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