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.
//版本一:使用map容器,统计并记录每个元素的个数
public int majorityElement(int[] nums) {
//将数组的每个元素及其对应的个数构成<key,value>对,存入map容器
HashMap<Integer, Integer> map = new HashMap<>();
int threshold = nums.length / 2;
int tempCount = 1;
for(int ele : nums) {
//如果该元素已经存在于map中,判断该元素的个数是否超过半数
//如果已经达到半数,即找到了Majority Element,否则将其个数加1
if(map.containsKey(ele)) {
if((tempCount = map.get(ele) + 1) > threshold)
return ele;
map.put(ele, tempCount);
}else
map.put(ele, 1);
}
//如果nums数组中只有一个元素,则直接返回该元素(否则该语句不会被执行)
return nums[0];
}
//版本二:将数组排序,使相同元素挨在一起,再统计各个元素的个数
public int majorityElement2(int[] nums) {
//将原数组排序
Arrays.sort(nums);
int tempCount = 1;
int tempNum = nums[0];
int len = nums.length - 1;
for(int i = 1; i < len; ++i) {
//统计当前元素出现的次数
tempNum = nums[i];
tempCount = 1;
while(i < len && tempNum == nums[i+1]) {
i++;
tempCount++;
}
//已知Majority Element必存在且唯一,如果满足条件则终止遍历
if(tempCount >= len/2) break;
}
return tempNum;
}