多数元素
给定一个大小为 n
的数组 nums
,返回其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
哈希表法
时间复杂度O(n)
空间复杂度O(n)
public int majorityElement(int[] nums) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int num : nums) {
Integer value = map.put(num, 0);
if(value != null && value >= (nums.length)/2){
return num;
}
map.put(num,value != null ? value+1 : 1);
}
return nums[0];
}
摩尔投票法
主要思想是,如果一个数组有一个数占了超过一半,那删除两个不同的数整个数组的众数不变
//摩尔投票法
//假设第一个为众数
//指针每次后移如果和众数不同就count++,不然就--
//如果count为0就换众数
//每次比较相当于两个数都被删除,整个数组的众数不变
public int majorityElement(int[] nums) {
int res = nums[0];
int count = 1;
int index = 0;
for (int i = 0; i < nums.length; i++) {
if(nums[index] == res){
count ++;
}else{
count --;
if(count == 0){
res = nums[index];
count = 1;
}
}
index ++;
}
return res;
}