题目要求:
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记录每个元素出现的次数,然后判断这个元素出现的次数如果超过一半,就返回
public class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<Integer, Integer>();
for(int i=0;i<nums.length;i++)
{
if(!map.containsKey(nums[i]))
{
map.put(nums[i],1);
}else
{
int value = map.get(nums[i]);
value++;
map.replace(nums[i],value);
}
}
for(int i=0;i<nums.length;i++)
{
if(map.get(nums[i])>nums.length/2)
{
return nums[i];
}
}
return 0;
}
}