169. Majority Element (Easy)

来源:互联网 发布:windows nt3.1 编辑:程序博客网 时间:2024/05/19 12:14

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:

Java:

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

思路,用Map保存每个数出现的次数,然后遍历map找出Majority Element。

0 0
原创粉丝点击