Java using HashMap


  • 0

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

        // num and occurrences
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> result = new ArrayList<>();    
        for (int num : nums) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }
        
        for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
            
            int key = entry.getKey();
            int value = entry.getValue();
            
            if (value > nums.length / 3) {
                result.add(key);
            }
        }
        return result;
    }
    

    }

    '''


Log in to reply
 

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