Simple java use hashset


  • 3
    S
    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            HashSet<Integer> set = new HashSet<Integer>();
            for( int i : nums){
            	if(set.contains(i))
            		return true;
            	else
            		set.add(i);
            }
            return false;
        }
    }

  • 0
    S

    similar one saw other and improve some code

    public boolean containsDuplicate(int[] nums) {
        HashSet<Integer> set = new HashSet<Integer>();
        for( int i : nums){
            set.add(i);
        }
        return set.size() < nums.length ? true : false;
    }

  • 6
    D
    public boolean containsDuplicate(int[] nums) {
        HashSet<Integer> set = new HashSet<>();
        for( int num : nums){
            if(!set.add(num)) return true;
        }
        return false;
    }

  • 0
    H
    public boolean containsDuplicate(int[] nums) {
        if(nums==null||nums.length==0)
          return false;
          if(nums.length==1)
          return false;
          int n=nums.length;
        HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
        for(int i=0;i<n;i++){
            if(map.get(nums[i])==null)
              map.put(nums[i],1);
              else
              return true;
        }
        return false;
        
    }

Log in to reply
 

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