LeetCode--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.
解決方案:
public class Solution {
public int majorityElement(int[] num) {
int n = num.length;
HashMap hsMap = new HashMap();
for (int i = 0; i < n; i++) {
if (hsMap.get(num[i]) == null) {
hsMap.put(num[i], 1);
if (1 > (n / 2)) {
return num[i];
}
} else // hsMap.get(num[i]) != null
{
if ((hsMap.get(num[i]) + 1) > (n / 2)) {
return num[i];
}
hsMap.put(num[i], hsMap.get(num[i]) + 1);
}
}
return -1;
}
}