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

Majority Element

时间:2015-04-08 21:28:09      阅读:101      评论: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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

https://leetcode.com/problems/majority-element/

 1 import java.util.Hashtable;
 2 
 3 
 4 public class Solution 
 5 {
 6 
 7     public static int majorityElement(int[] num)
 8     {
 9         Hashtable<Integer,Integer> ht=new Hashtable();
10         for(int i=0;i<num.length;i++)
11         {
12             if(ht.containsKey(num[i]))
13                 ht.put(num[i],ht.get(num[i])+1);
14             else
15                 ht.put(num[i],1);
16             if(ht.get(num[i])>=num.length/2)
17                 return num[i];    
18         }
19         return 0;
20     }
21 
22     public static void main(String args[])
23     {
24         int[] num={6,5,5};
25         System.out.println(majorityElement(num));
26     }
27 }

 

Majority Element

标签:

原文地址:http://www.cnblogs.com/qq1029579233/p/4403502.html

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