"Leetcode" Major Element in JAVA

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.