Problem

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.

Solution

class Solution {
    public int majorityElement(int[] nums) {
        if (nums == null || nums.length == 0) return -1;
        Map<Integer, Integer> map = new HashMap<>();
        for (int num: nums) {
            if (map.containsKey(num)) {
                if (map.get(num)+1 > nums.length/2) {
                    return num;
                } else {
                    map.put(num, map.get(num)+1);
                }
            } else {
                map.put(num, 1);
            }
        }
        return -1;
    }
}

update 2018-11

class Solution {
    public int majorityElement(int[] nums) {
        int count = 0;
        int res = nums[0];
        for (int num: nums) {
            if (count == 0) {
                res = num;
                count++;
            } else if (num == res) {
                count++;
            } else {
                count--;
            }
        }
        return res;
    }
}

linspiration
161 声望53 粉丝