Straight forward solution using Hashmap


  • -1
    L

    public class Solution {
    public List<Integer> majorityElement(int[] nums) {

        Map<Integer, Integer> map = new HashMap<>();
        
        for(int i=0;i<nums.length;i++){
            if(!map.containsKey(nums[i])){
                map.put(nums[i],1);
            }else{
                int value = map.get(nums[i]);
                map.put(nums[i],value+1);
            }
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        for(Map.Entry<Integer, Integer> m: map.entrySet()){
            if(m.getValue()>nums.length/3){
                list.add(m.getKey());
            }
        }
     
        return list;
        
    
    }
    

    }


  • 2
    J

    obviously this is not O(1) space


  • 0
    S

    I submitted an answer almost the same as his and it was OK'd by the judge...
    .
    I think you're right about the space complexity though. It's 0(n) and not the 0(1) as requested.


Log in to reply
 

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