码迷,mamicode.com
首页 > 其他好文 > 详细

169. Majority Element

时间:2017-01-14 15:47:50      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:hash   元素   else   允许   return   长度   题目   code   time   

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.

题目大意

给定size 为n的数组,查找出主元素,就是出现次数大于n/2次的元素。你可以假定数组非空,而且主元素一定存在。

解题思路:
(1)使用HashMap,Map的特点:不允许重复元素,因此在存储前需要判断是否存在
(2)判断HashMap中存在nums[i],如果存在,使用hm.get(nums[i])获取value,即通过key来获得value值,即count(出现的次数)
(3)如果count大于数组长度的一般,即返回该元素
(4)如果count不满足条件,向HashMap存储元素以及出现的次数。

 1  /* Map的特点:不允许重复元素,因此在存储前需要判断是否存在         */    
 2          Map<Integer, Integer> hm=new HashMap<Integer, Integer>();        
 3          for (int i = 0; i < nums.length; i++)        
 4          {            
 5              int count=0;            
 6              //判断HashMap中存在nums[i],如果存在,使用hm.get(nums[i])获取value            
 7              //即通过key来获得value值,即count(出现的次数)        
 8              if (hm.containsKey(nums[i]))            
 9              {                
10                  count=hm.get(nums[i])+1;            
11                  
12              }            
13              else            
14              {                
15                  count=1;            
16                  
17              }            
18              //如果count大于数组长度的一般,即返回该元素            
19              if (count>nums.length/2)            
20              {                
21                  return nums[i];        
22                  }            
23                  //向HashMap存储元素以及出现的次数        
24                  hm.put(nums[i], count);    
25                  }        
26                  return 0;    

169. Majority Element

标签:hash   元素   else   允许   return   长度   题目   code   time   

原文地址:http://www.cnblogs.com/sunli0205/p/6285330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!