题目描述
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.
思路分析
方法一:
题目对空间没有限制,则可以通过一次遍历把它存在HashMap中,然后再查找HashMap中value值大于n/2的key值。
方法二:
空间上可以进行优化,不借助hashmap,这里我们可以使用一个count进行计数,初始值为0。假定nums[0]即为个数超过一半的值res = nums[0]。遍历数组,如果nums[i]等于res,则count++,当count为0时,则重新选定可能的最大频繁项,即res=nums[i],否则count- -。
这里如果存在个数超过一半的数值,则一定是res。
代码
方法一:
public static int majorityElement(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if(map.get(nums[i]) != null)
{
map.put(nums[i],map.get(nums[i]) + 1);
}else
{
map.put(nums[i], 1);
}
}
for (int key : map.keySet()) {
if(map.get(key) > nums.length / 2)
{
return key;
}
}
return 0;
}
方法二:
public int majorityElement(int[] nums) {
int count = 0,res = nums[0];
for (int i = 0; i < nums.length; i++) {
if(nums[i] == res)
{
count++;
}else if(count == 0)
{
res = nums[i];
}else{
count -- ;
}
}
return res;
}