给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3] 输出: 3
示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
方法1
分析:通过众数的性质可知,如果一个数是众数,通过排序之后那么该众数必然等于=nums[(int)Math.floor(nums.length/2)]。时间复杂度O(n)
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int floor=(int)Math.floor(nums.length/2);
int count=0;
for(int i=0;i<nums.length;i++) {
if(nums[i]==nums[floor])
count++;
if(count>floor) {
return nums[floor];
}
}
return 0;
}
}
方法2
分析:将数组元素放入Map<Integer,Integer>中,重复的value+1.时间复杂度O(n)
class Solution {
public int majorityElement(int[] nums) {
//Map<数组元素,出现次数>
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++) {
if(map.containsKey(nums[i])) {
map.put(nums[i], map.get(nums[i])+1);
}else {
map.put(nums[i], 1);
}
}
int floor=(int)Math.floor(nums.length/2);
for(Map.Entry<Integer, Integer> s:map.entrySet()) {
if(s.getValue()>floor) {
System.out.println(s.getKey());
return s.getKey();
}
}
return 0;
}
}
方法3
分析:摩尔投票法,在每一轮投票过程中,从数组中找出一对不同的元素,将其从数组中删除。这样不断的删除直到无法再进行投票,如果数组为空,则没有任何元素出现的次数超过该数组长度的一半。如果只存在一种元素,那么这个元素则可能为目标元素。
class Solution {
public int majorityElement(int[] nums) {
int count = 1;
int maj = nums[0];
for(int i = 1; i <nums.length; i++)
{
if(nums[i] == maj)
count++;
else{
count --;
if(count == 0)
{
maj = nums[i];
count = 1;
}
}
}
return maj;
}
}