原题网址:https://leetcode.com/problems/majority-element/
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
方法一:使用哈希映射统计。
public class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> counts = new HashMap<>();
for(int num: nums) {
Integer count = counts.get(num);
if (count == null) count = 1; else count ++;
if (count > nums.length/2) return num;
counts.put(num, count);
}
return nums[0];
}
}
方法二:统计各个比特。
public class Solution {
public int majorityElement(int[] nums) {
int majority = 0;
int half = nums.length/2;
for(int i=0; i<32; i++) {
int count = 0;
int b = 1 << i;
for(int num:nums) {
if ((num & b) != 0) count ++;
if (count > half) {
majority |= b;
break;
}
}
}
return majority;
}
}
也可以一次统计多个比特。
public class Solution {
public int majorityElement(int[] nums) {
int half = nums.length/2;
int[][] counts = new int[8][16];
int[] majority = new int[8];
for(int i=0; i<8; i++) {
for(int num: nums) {
int hash = (num >> (i*4)) & 0b1111;
counts[i][hash] ++;
if (counts[i][hash] > half) {
majority[i] = hash;
break;
}
}
}
int result = 0;
for(int i=0; i<8; i++) {
result |= (majority[i] << (i*4));
}
return result;
}
}
方法三:设置两个缓冲变量。
public class Solution {
public int majorityElement(int[] nums) {
int m1=0, m2=0;
int c1=0, c2=0;
int half = nums.length/2;
for(int num:nums) {
if (c1==0) {
m1=num;
c1=1;
if (c1>half) return m1;
} else if (m1==num) {
c1++;
if (c1>half) return m1;
} else if (c2==0) {
m2=num;
c2=1;
if (c2>half) return m2;
} else if (m2==num) {
c2++;
if (c2>half) return m2;
} else if (c1<c2) {
m1=num;
c1=1;
if (c1>half) return m1;
} else {
m2=num;
c2=1;
if (c2>half) return m2;
}
}
if (c1>c2) return m1;
return m2;
}
}
方法四:摩尔投票算法。
public class Solution {
/*
http://www.programcreek.com/2014/02/leetcode-majority-element-java/
*/
public int majorityElement(int[] nums) {
int maj = nums[0];
int count = 1;
for(int num: nums) {
if (maj == num) {
count ++;
} else {
count --;
if (count == 0) {
maj = num;
count = 1;
}
}
}
return maj;
}
}