Java solution using HashMap


  • 0
    Q
    public class Solution {
        public int singleNumber(int[] nums) {
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i=0;i<nums.length;i++){
                int n = nums[i];
                if (map.containsKey(n)){
                    int val = map.get(n);
                    if (val == 1){
                        map.put(n, 2);
                    }
                    else{
                        map.remove(n);
                    }
                }
                else{
                    map.put(n, 1);
                }
            }
            return map.keySet().iterator().next();
        }
    }

  • 0
    Q

    Just realized this would not work if the number that doesn't appear 3 times appears multiple of 3. For example, 6 times or 9 times. Test cases should have included such a use case.
    Instead of removing in main loop will need an extra loop that removes all keys with value == 3 from the Map.


  • 0
    D

    Try this maybe. It's still slow.

    public int singleNumber(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums){
            map.put(i, map.get(i) == null ? 1 : map.get(i) + 1);
            if (map.get(i) % 3 == 0){
                map.remove(i);
            }
        }
        return (int)map.keySet().toArray()[0];
    }

Log in to reply
 

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