Saturday, September 16, 2017

217. Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Solution:
Very easy, I think people should solve this in one pass.
Time complexity O(n), Extra space O(n)
 public boolean containsDuplicate(int[] nums) {  
     HashSet<Integer> set=new HashSet();  
     for(int i=0;i<nums.length;i++){  
       if(!set.add(nums[i])) return true;  
     }  
     return false;  
   }  

No comments:

Post a Comment