zoukankan      html  css  js  c++  java
  • 169. Majority Element

    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/2 ⌋的元素。 假设给定的数组非空,主元素都存在。 

     1     public int majorityElement(int[] nums) {
     2         Map<Integer, Integer> numberMap = new HashMap<>();
     3         for (int i = 0; i < nums.length; i++) {
     4             numberMap.put(nums[i], numberMap.getOrDefault(nums[i], 0)+1);
     5         }
     6         int level = (nums.length+1)/2;
     7         for (Map.Entry<Integer, Integer> e : numberMap.entrySet()) {
     8             if (e.getValue() >= level) {
     9                return e.getKey();
    10             }
    11         }
    12         return Integer.MIN_VALUE;        
    13     }
  • 相关阅读:
    JZOJ 5870 地图
    20190921
    20190919
    SP703 SERVICE
    UVA323 Jury Compromise
    [note]一类位运算求最值问题
    [BZOJ3674]可持久化并查集
    [luogu3359]改造异或树
    [luogu4755]Beautiful Pair
    [BJWC2012]冻结
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7668617.html
Copyright © 2011-2022 走看看