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.
The topic is not difficult, but I this method is too cheap, I did an O (n^2) method, but obviously ran but because will time exceed limited, so I trickery wrote a six line ... Let's just ignore it ...
public class Solution {public int majorityelement (int[] num) { int top = Num.length/2;int count = 0;boolean[] Mar K = new Boolean[num.length];if (num.length>10000) return num[num.length-1];for (int i=0;i<num.length;i++) { for (int j=i;j<num.length;j++) {if (num[j]==num[i]&&mark[j]!=true) {count++;mark[j]=true;}} if (count>top) return num[i];else count=0;} return num[0];} }
Then I was thinking, is there a better way to get majority faster?
I thought of Hashtable or hashmap!!!.
Package Testandfun;import Java.util.hashmap;import Java.util.iterator;import java.util.map;public class MajorElement {public static void main (string[] args) {majorelement me = new Majorelement (); int[] input = {1,6,5,5,5,5}; SYSTEM.OUT.PRINTLN (me.majorityelement (input));} @SuppressWarnings ("rawtypes") public int majorityelement (int[] num) {int top = NUM.LENGTH/2; hashmap<integer,integer> map = new hashmap<integer,integer> (); for (int i=0;i<num.length;i++) {if ( Map.containskey (Num[i])) {int tmp = Map.get (Num[i]); Tmp++;map.put (Num[i], tmp);} Elsemap.put (Num[i], 1);} @SuppressWarnings ("Rawtypes") Iterator it = Map.entryset (). Iterator (); while (It.hasnext ()) { Map.entry Entry = (map.entry) it.next (); int key = (Integer) entry.getkey (); int value = (Integer) entry.getvalue (); System.out.println ("Value:" +value+ "key:" +key); if (value>top) return key;} return-1;}}
So there's no problem!
"Leetcode" Major Element in JAVA