问:
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且数组中的众数永远存在。
此题除了暴力计算出现次数之外有两种解法,一种是先排序,然后因为众数出现次数大于数组的一半所以中间那个肯定是众数,还有一种是动态规划,用一个count计算出现的次数,相同+1,不同-1,如果count为0了说明应该换一个数找了,因为众数出现的次数大于数组的一半,所以一旦找到那个数count就不会被减到为0。
下面是第一种解法,耗时3ms。
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int len=nums.length;
return nums[len/2];
}
}
第二种解法,耗时2ms。
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int candidate = 0;
for (int i = 0; i < nums.length; i++) {
if (count == 0) //目前得到的数出现次数为0时,更换另外一个数
{
candidate = nums[i];
count = 1;
} else {
if (candidate == nums[i])
count++; //相同+1
else
count--; //不同-1,
}
}
//检验找到的是否真是众数
count = 0;
for (int i = 0; i < nums.length; ++i) {
if (candidate == nums[i])
count++;
}
if (count > nums.length / 2)
return candidate;
else
return -1;
}
}