Easy solution using maps


  • 0
    E

    Go through the array using the for loop ( i in array )
    if array[i] not in map
    add Key=array[i] & value=1
    else
    value++

    it will take o(n) as time complexity and o(n) space

    public class Solution {
        public int singleNumber(int[] nums) {
            
            
             Map<Integer,Integer> map=new HashMap<Integer,Integer>();
            
            for(int i=0;i<nums.length;i++)
                if(map.get(nums[i]) ==null)
                    map.put(nums[i],1);
            else
                map.put(nums[i],map.get(nums[i])+1);
            
             for (Map.Entry<Integer, Integer> entry : map.entrySet())
                 if(entry.getValue() == 1)
                     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.