5 lines in Java


  • 49
    R

    The Set's add method can be used for this situation,because it will return false if the element already exists .

    public  boolean containsDuplicate(int[] nums) {
    		 Set<Integer> set = new HashSet<Integer>();
    		 for(int i : nums)
    			 if(!set.add(i))// if there is same
    				 return true; 
    		 return false;
    	 }

  • 0
    L

    very good!,thanks your answer


  • 2
    G

    This is not a good answer. Try submitting it and see for yourselves.


  • 1
    S

    No, this is a good answer. It doesn't make sense for the question to add new time restriction. As long as it is O(n), it should be fine.


  • 0
    T

    Your solution is clever. Using add() method to check duplicates is more time efficient I think!
    Since I tried to use the same solution as method 3 in this post. But I got a TLE error without the 'final' keyword. I don't know why.T_T


  • 0
    R

    Also using Hash Set to solve this problem, but I used size() to compared the size of set is equal to the length of the array or not.

    public  boolean containsDuplicate(int[] nums) {	
          HashSet h = new HashSet();
          for (int i=0;i<nums.length;i++){
    		h.add(nums[i]);
          }
          return (h.size()!=nums.length)? true:false;
    }

  • 0
    G

    @riskycheng yes,if you use Set,you just need to compare the length of them,if nums contains any duplicates ,the length of Set will be reduced,so this is my code:

    public class Solution {
        public boolean containsDuplicate(int[] nums) {
          Set<Integer> set=new HashSet<>();
          for(Integer num:nums) set.add(num);
          return !(set.size()==nums.length);
        }
    }
    

  • 0
    S

    Java 8 one liner, not so fast though:

    class Solution {
        public boolean containsDuplicate(int[] nums) {
            return Arrays.stream(nums).distinct().count() < nums.length;
        }
    }
    

Log in to reply
 

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