First Thoughts: first calculate the majority element requirement count. As we create the hash map (integer counts), we can - at the same time - check by retrieving and checking if the current count is greater than majority requirement count. And if satisfied, directly return value. Because it will always exist in the array, it will always return something. Last return statement to simply avoid compile error.
My Solution:
class Solution {
public int majorityElement(int[] nums) {
int majorNum = nums.length/2;
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums){
map.putIfAbsent(num, 0);
map.put(num, map.get(num)+1);
if (map.get(num)>majorNum) return num;
}
return 0;
}
}