Using Hashing - Simple Java Solution


  • 0
    V
    public class Solution {
        public List<Integer> majorityElement(int[] nums) {
            List<Integer> result=new ArrayList<Integer>();
            if(nums==null)
                return result;
            int poten_val=nums.length/3;
            int n=nums.length;
            HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
            for(int i=0;i<n;i++)
            {
                map.put(nums[i],map.getOrDefault(nums[i],0)+1);
                if(map.getOrDefault(nums[i],0) > poten_val && !result.contains(nums[i]))
                    result.add(nums[i]);
               
            }
            return result;
        }
    }
    

Log in to reply
 

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