JAVA solution--easy and clear using HashMap


  • 0
    J
    public class Solution {
    public int[] singleNumber(int[] nums) {
        if(nums.length==2){
            return nums;
        }
        HashMap<Integer, Integer> map= new HashMap<Integer,Integer>();
        int [] result=new int[2];
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(nums[i])){map.put(nums[i],2);}
            else{
                map.put(nums[i],1);
            }
            
        }
        for(int i=0;i<nums.length;i++){
            if(map.get(nums[i])!=2){
                if(result[0]!=0){result[1]=nums[i];}
                else{result[0]=nums[i];}
                
            }
        }
        return result;
    
    }
    

    }


Log in to reply
 

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