Basic idea of the algorithm is if we cancel out each occurrence of an element e with all the other elements that are different from e then e will exist till end if it is a majority element.
publicclassSolution{ publicintmajorityElement(int[] nums){ int cur = nums[0], count = 0; for (int i = 0; i < nums.length; i++){ if (count == 0){ cur = nums[i]; count++; }elseif (nums[i] == cur){ count++; }elseif (nums[i] != cur){ count--; } } // can add a second O(n) pass to confirm that this number is // indeed the majority element by counting its frequency return cur; } }
Randomization, 3ms
Adapted from Leetcode Discussion Board
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import java.util.Random; publicclassSolution{ publicintmajorityElement(int[] nums){ int length = nums.length; Random rd = new Random(); while (true){ int idx = rd.nextInt(length); int candidate = nums[idx]; int count = 0; for (int i = 0; i < length; i++){ if (nums[i] == candidate) count++; } if (count > length / 2) {return candidate;} } } }
Bit Manipulation
Cited from Leetcode Discussion Board
1 2 3 4 5 6 7 8 9 10 11 12 13
publicintmajorityElement(int[] nums){ int[] bit = newint[32]; for (int num: nums) for (int i=0; i<32; i++) if ((num >> (31-i) & 1) == 1) bit[i]++; int ret=0; for (int i=0; i<32; i++) { bit[i]= bit[i]>nums.length/2 ? 1 : 0; ret += bit[i]*(1<<(31-i)); } return ret; }
or
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicintmajorityElement(int[] num){ int ret = 0;
for (int i = 0; i < 32; i++) { int ones = 0, zeros = 0; for (int j = 0; j < num.length; j++) { if ((num[j] & (1 << i)) != 0) { ++ones; } else ++zeros; } if (ones > zeros) ret |= (1 << i); }