首页 > 其他 > 详细

169. Majority Element

时间:2017-10-14 21:42:11      阅读:307      评论:0      收藏:0      [点我收藏+]

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     }

 

169. Majority Element

原文:http://www.cnblogs.com/wzj4858/p/7668617.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!