Most easiest solution in Java with Hashmap


  • 0
    P

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


Log in to reply
 

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