Topic
Given an array of size n, find the majority element. The majority element is the element, the appears more than times ? n/2 ? .
Assume that the array was 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.
Code
Import Java.util.hashtable;import Java.util.iterator;public class Solution {public int majorityelement (int[] num) { hashtable<integer,integer> rightlist = new hashtable<integer,integer> (); for (int i=0;i<num.length;i++) { if (Rightlist.get (Num[i]) ==null) { rightlist.put (num[i], 1); } else{ rightlist.put (Num[i], Rightlist.get (Num[i]) +1); } } int result_value=0; int result_key=0; for (Iterator ITR = Rightlist.keyset (). Iterator (); Itr.hasnext ();) { int key = (Integer) itr.next (); if (Rightlist.get (key) >result_value) { result_key=key; Result_value=rightlist.get (key); } } return result_key;} }
Code Download:Https://github.com/jimenbian/GarvinLeetCode
/********************************
* This article from the blog "Bo Li Garvin"
* Reprint Please indicate the source : Http://blog.csdn.net/buptgshengod
******************************************/
"Leetcode from zero single row" no.169 Majority Element (hashmap usage)