Why my Java solution cannot deal with HashMap????


  • 0
     Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
            List<Integer> result = new ArrayList<Integer>();
            for(int cur:nums){
                if(!myMap.containsKey(cur)){
                    myMap.put(cur,1);
                }
                else{
                    myMap.put(cur,myMap.get(cur)+1);
                }
                if(myMap.get(cur)>nums.length/3){
                    result.add(cur);
                    break;
                }
            }
            return result;

  • 0
    Z

    you need to find all numbers( max 2 numbers) which count > (length / 3), not just the first number


  • 0
    A

    Because the majority number maybe more than one, you have to find all of them. You can check the value of all numbers to decide which numbers should be added to your result list, or you can also add it to result list as your way but set the value of this number to Integer.MAX_VALUE to avoid add duplicates and without "break". But, I suggest the former.


Log in to reply
 

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