Java8 3 lines O(n) solution


  • -7
    D
     public static List<Integer> majorityElement(int[] nums) {
        HashMap<Integer, Integer> result = new HashMap<>();
        Arrays.stream(nums).forEach(x -> result.put(x, result.containsKey(x) ? result.get(x) + 1 : 1));
        return result.entrySet().stream().filter(entry -> entry.getValue() > nums.length / 3).map(Map.Entry::getKey).collect(Collectors.toList());
    }

  • 0
    V

    looks straightforward but breaks the rule: "The algorithm should run in linear time and in O(1) space"


Log in to reply
 

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