## Sunday, March 27, 2016

### LeetCode 217 - Contains Duplicate

LeetCode 219 - Contains Duplicate II
LeetCode 217 - Contains Duplicate
LeetCode 220 - Contains Duplicate III
https://leetcode.com/discuss/37219/possible-solutions
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.
Using HashSet
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>(nums.length);
for (int x: nums) {
if (set.contains(x)) return true;
}
return false;
}
http://www.programcreek.com/2014/05/leetcode-contains-duplicate-java/
 public boolean containsDuplicate(int[] nums) { if(nums==null || nums.length==0) return false;   HashSet set = new HashSet(); for(int i: nums){ if(!set.add(i)){ return true; } }   return false; }
def containsDuplicate(self, nums): numSet = set() for num in nums: if num in numSet: return True numSet.add(num) return False

def containsDuplicate(self, nums): return len(nums) != len(set(nums))
Sorting
public boolean containsDuplicate(int[] nums) {
Arrays.sort(nums);
for (int i = 0; i < nums.length - 1; ++i) {
if (nums[i] == nums[i + 1]) return true;
}
return false;
}

public boolean containsDuplicate(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] == nums[i]) return true;
}
}
return false;
}

JDK8:
public boolean containsDuplicate(int[] nums) { return nums.length != Arrays.stream(nums) .distinct() .count(); }

public boolean containsDuplicate(int[] nums) { Set<Integer> seen = new HashSet<>(); return Arrays.stream(nums).anyMatch(num -> !seen.add(num)); }
Using BitSet must be converting negative numbers in binary to decimal.