Skip to content

217. Contains Duplicate

Jacky Zhang edited this page Aug 11, 2016 · 1 revision

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.

##Approach 1: sorting

public class Solution {
    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;
    }
}

##Approach 2: hash table

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> hs = new HashSet<Integer>();
        for(int num : nums) {
            if(hs.contains(num)) return true;
            hs.add(num);
        }
        return false;
    }
}
Clone this wiki locally