链接
思路
map
遍历数组,同时用一个map的键来存储数组中出现的数,用map的值来存储数的出现次数,最后,遍历map,如果map中某个键对应的值超过了数组的一半,则将其返回,由于题目设置,势必存在,在循环外返回-1(即数组中没有一个数出现次数超过数组中数字的一半)
摩尔投票
遍历数组,如果count 为0,则将该数赋值给card,然后遍历之后的数字,相同则加1,不同则减一,遍历完成之后,card 即为数组中超过板书的数字
排序
先将数组进行排序,然后返回中间元素
代码
map
class Solution {
public int majorityElement(int[] nums)
{
Map<Integer, Integer> map = new TreeMap<>();
for (int num : nums)
{
if (!map.containsKey(num))
{
map.put(num, 0);
} else
{
map.put(num, map.get(num) + 1);
}
}
//
int n = nums.length / 2;
for (int num : nums)
{
if (map.get(num) >= n)
{
return num;
}
}
return -1;
}
}
摩尔投票
class Solution {
public int majorityElement(int[] nums)
{
if (nums.length <= 0)
{
return -1;
}
int count = 0;
Integer card = null;
for (int num : nums)
{
if (0 == count)
{
card = num;
}
count += (card == num) ? 1 : -1;
}
return card;
}
}
排序
class Solution {
public int majorityElement(int[] nums)
{
Arrays.sort(nums);
return nums[nums.length / 2];
}
}