My simple hashmap java solution 320ms


  • 0
    S

    The requested element can be return when it is dealt with. It saves running time.

    public class Solution {
        public int majorityElement(int[] num) {
            HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
            if(num.length == 1) return num[0];
            for(int i=0; i<num.length; i++) {
                if(!hm.containsKey(num[i])) {
                    hm.put(num[i], 1);
                } else {
                    hm.put(num[i], hm.get(num[i])+1);
                    if(hm.get(num[i]) > num.length/2) return num[i];
                } 
            }
            return -1;
        }
    }

  • 4
    W
    public class Solution {
      public int majorityElement(int[] num) {
        Arrays.sort(num);
        return num[num.length / 2];
      }
    }

  • 0
    P

    Holy shit! What a " more than n/2 times“!


  • 0
    G

    I doubt if it's the main purpose of this problem...But SMART!


  • 0
    S

    many people have posted this answer long ago, I think it has been nothing


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.