Java Solution using HashMap


  • 0
    C
    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            HashMap<Integer,Integer> hmap = new HashMap<Integer,Integer>(); 
            for(int i=0;i<nums.length;i++)
            {
                if(hmap.containsKey(nums[i]))
                hmap.put(nums[i],hmap.get(nums[i])+1);
                else
                hmap.put(nums[i],1);
            }
            for(int i=0;i<nums.length;i++)
            {
                if(hmap.get(nums[i]) != 1)
                return true;
            }
            return false;
        }
    }

  • 0
    L

    it didn't time limit exceeded ?


  • 0
    L
    public class Solution {
    public boolean containsDuplicate(int[] nums) {
        HashMap<Integer,Integer> hmap = new HashMap<Integer,Integer>(); 
        for(int i=0;i<nums.length;i++)
        {
            if(hmap.containsKey(nums[i]))
            {
                return true;
            } 
            else{
                    hmap.put(nums[i],1);
            }
        }
        return false;
    }
    

    }

    it seemed that didn't time limit exceeded


  • 0
    J

    Alternatively, you could just use a hashset


Log in to reply
 

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