What about HashTable


  • 0
    Z

    The first method in my mind is the HashTable.
    I compared the result with hashtable and normal sorting method in JAVA, the hashtable take longer time.

    So,my question is during the interview, if i tried the hashtable, will the interviewer consider my answer fail?
    Thanks.


  • 0
    A

    I wouldn't think so. HashTable has the same big O it's just more space and more complex. It would definitely be better if you give out the smarter way most people use. I just passed my solution with hashtable, below is my code:

    public class Solution {
          public static int majorityElement(int[] nums) {
                Map<Integer,Integer> hash = new HashMap<Integer,Integer>();
                for (int elem: nums)
                	if (!hash.containsKey(elem))
                		hash.put(elem,0);
                	else
                		hash.put(elem,hash.get(elem)+1);
                for (Map.Entry<Integer,Integer> entry: hash.entrySet())
                	if (entry.getValue() >= nums.length/2)
                		return entry.getKey();
            	return 0;
            }
        }

Log in to reply
 

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