Leet Code OJ 169. Majority Element [Difficulty: Easy]

题目:
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.

思路分析:
题意是给定一个长度为n的数组,找出“主要元素”。“主要元素”指的是出现次数大于⌊ n/2 ⌋的元素。

代码实现:

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

你可能感兴趣的:(算法)