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.

    Example 1:

    1. Input: [3,2,3]
    2. Output: 3

    Example 2:

    1. Input: [2,2,1,1,1,2,2]
    2. Output: 2

    题意

    找到数组中出现次数超过一半的元素。

    思路

    1. 直接用HashMap记录每一个元素出现的次数;
    2. 先将数组排序,则此时数组的中位数就是要求的元素x(因为x出现次数大于n/2);
    3. 位运算,统计所有数字每一位上1和0的个数,则目标数字x对应位上的值是其中个数较多的那一个;
    4. Boyer-Moore Majority Vote

    代码实现 - Hash

    1. class Solution {
    2. public int majorityElement(int[] nums) {
    3. Map<Integer, Integer> map = new HashMap<>();
    4. for (int i = 0; i < nums.length; i++) {
    5. int x = nums[i];
    6. map.put(x, map.getOrDefault(x, 0) + 1);
    7. if (map.get(x) > nums.length / 2) {
    8. return x;
    9. }
    10. }
    11. return 0;
    12. }
    13. }

    代码实现 - 排序

    1. class Solution {
    2. public int majorityElement(int[] nums) {
    3. Arrays.sort(nums);
    4. return nums[nums.length / 2];
    5. }
    6. }

    代码实现 - 位运算

    1. class Solution {
    2. public int majorityElement(int[] nums) {
    3. int ans = 0;
    4. for (int i = 0; i < 32; i++) {
    5. int ones = 0, zeros = 0;
    6. for (int num : nums) {
    7. if (ones > nums.length/2 || zeros > nums.length / 2) break;
    8. if ((num & (1 << i)) != 0) ones++;
    9. else zeros++;
    10. }
    11. if (ones > zeros) {
    12. ans = ans | (1 << i);
    13. }
    14. }
    15. return ans;
    16. }
    17. }

    代码实现 - Boyer-Moore Majority Vote

    1. class Solution {
    2. public int majorityElement(int[] nums) {
    3. int count = 0;
    4. int ans = nums[0];
    5. for (int i = 0; i < nums.length; i++) {
    6. if (count == 0) {
    7. ans = nums[i];
    8. count++;
    9. } else {
    10. count += nums[i] == ans ? 1 : -1;
    11. }
    12. }
    13. return ans;
    14. }
    15. }