Java simplification using HashMap ,easy to understand


  • 0
    P

    public int[] singleNumber(int[] nums) {
    Arrays.sort(nums);
    int[]num=new int[2];
    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 && i<2)
    {
    num[i]=(Integer)pair.getKey();
    i++;
    }
    }
    return num;
    }


Log in to reply
 

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