Easy to understand Java HashMap based solution


  • 0
    P
         public int singleNumber(int[] nums) {
        
         Arrays.sort(nums);
        int num=0;
        HashMap<Integer,Integer>hash=new HashMap<Integer, Integer>();
        for(int i=0;i<nums.length;i++)
        {
        	if(hash.containsKey(nums[i]))
        	{
        		hash.put(nums[i],hash.get(nums[i])+1);
        	}
        	else
        	{
        		hash.put(nums[i],1);
        	}
        }
        Iterator it=hash.entrySet().iterator();
        int i=0;
        while(it.hasNext())
        {
        	Map.Entry pair = (Map.Entry)it.next();
        	Integer k= (Integer) pair.getValue();
        	if(k==1)
        	{
        		num =(Integer)pair.getKey();
                return num;
        		
        	}
        }
        return 1;
    }

Log in to reply
 

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