Skip to content

Instantly share code, notes, and snippets.

@iamdejan
Last active May 6, 2020 09:57
Show Gist options
  • Save iamdejan/b89a42e39bd5beb0db7be085ce2883b8 to your computer and use it in GitHub Desktop.
Save iamdejan/b89a42e39bd5beb0db7be085ce2883b8 to your computer and use it in GitHub Desktop.
Majority Element - Leetcode May 30-Day Challenge

Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than [n/2] times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for(int n: nums) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
int majority = nums.length / 2;
for(Map.Entry<Integer, Integer> entry: map.entrySet()) {
if(entry.getValue() > majority) {
return entry.getKey();
}
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment