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.

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 }
原文地址:https://www.cnblogs.com/qq1029579233/p/4403502.html