输入:一个数组
输出:数组中的众数
规则:众数就是出现次数大于数组长度一半的元素。
分析:暴力,计算每个元素出现次数。
public int majorityElement(int[] nums) {
for(int num : nums){
int count = 0;
for(int num2 : nums){
if(num == num2) count++;
}
if(count>= nums.length/2) return num;
}
return -1;
}
分析2:Boyer-Moore 投票算法。不得不说这个方法太巧妙了。就像是投赞成票和反对票。最后总会有一方赢了,因为题目说了众数总是存在的。
public int majorityElement(int[] nums) {
int candidate = nums[0];
int count = 0;
for(int num : nums){
if(count==0){
candidate = num;
}
count += (candidate == num?1:-1);
}
return candidate;
}
分析3:Hash
public int majorityElement(int[] nums) {
Map<Integer,Integer> countMap = new HashMap<Integer,Integer>();
for(int num : nums){
if(countMap.get(num)==null){
countMap.put(num,1);
}else{
countMap.put(num,1+countMap.get(num));
}
}
for(Integer key : countMap.keySet()){
if(countMap.get(key) > (nums.length/2)){
return key;
}
}
return 0;
}
分析4:位运算。一个int有32位。对于众数来讲,同一个位置上1的出现次数肯定也是大于数组长度一半的。
例如:数组3 2 2,众数是2。他们的二进制分别为
11
10
10
bitCount[0]=1,bitCount[1]=3。因为 b i t C o u n t [ 1 ] > 3 / 2 bitCount[1]>3/2 bitCount[1]>3/2,所以最后根据bitCount得到 的值是2。
public int majorityElement(int[] nums) {
int[] bitCount = new int[32];
for(int num : nums){
for(int i=0;i<32;i++){
if(((num>>i)&1) ==1){
bitCount[i]++;
}
}
}
int t = nums.length/2;
int r = 0;
for(int i=0;i<32;i++){
if(bitCount[i]>t){
r += (1<<i);
}
}
return r;
}
分析5:分治算法。数组从low到middle可以找到一个众数leftValue,数组从middle+1到high也可以找到一个众数rightValue。如果二者相等,则众数等于leftValue(rightValue也对)。如果不同,则需要数一数哪个值的个数多,结果就是哪个。当数组长度为1的时候,众数就是自己。
public int majorityElement(int[] nums) {
return majorityElement(nums, 0, nums.length-1);
}
private int majorityElement(int[] nums, int low, int high){
if(low == high) return nums[low];
int middle = (low + high) >> 1;
int leftValue = majorityElement(nums, low, middle);
int rightValue = majorityElement(nums, middle+1, high);
if(leftValue == rightValue) return leftValue;
int leftCount = count(nums, low, middle, leftValue);
int rightCount = count(nums, middle+1, high, rightValue);
return leftCount > rightCount ? leftValue: rightValue;
}
private int count(int[] nums, int low, int high, int val){
int c = 0;
for(int i=low; i<=high; i++){
if(nums[i] == val){
c ++;
}
}
return c;
}
参考链接:力扣官网