Java solution hashmap


  • -7
    public class Solution {
        public List<Integer> majorityElement(int[] nums) {
            
            List<Integer> result = new ArrayList<>();
            
            if(nums.length==0) return result;
            
            HashMap<Integer, Integer> hm = new HashMap<>();
            
            for(int i=0; i<nums.length; i++){
                if(hm.containsKey(nums[i])){
                    hm.put(nums[i],hm.get(nums[i])+1);
                }else{
                    hm.put(nums[i],1);
                }
            }
            for(int key: hm.keySet()){
                if(hm.get(key)>nums.length/3) result.add(key);
            }
            
            return result;
        }
    }

  • 0
    W

    Obviously it uses linear space


Log in to reply
 

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