Wednesday, August 26, 2015

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.
Solution1: Run time complexity of Arrays.sort is O(nlogn), so total run time complexity is O(nlogn), constant space. 
public class Solution {
    public boolean containsDuplicate(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return false;
        }
        
        Arrays.sort(nums);
        
        int i = 0;
        int j = i + 1;
        
        while (j < nums.length) {
            if (nums[i] == nums[j]) {
                return true;
            } else {
                i++;
                j++;
            }
        }
        return false;
    }
}
Solution2: Run time complexity is O(n), space complexity is O(n).
public class Solution {
    public boolean containsDuplicate(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return false;
        }
        
        HashSet set = new HashSet();
        for (int i = 0; i < nums.length; i++) {
            if (set.contains(nums[i])) {
                return true;
            } else {
                set.add(nums[i]);
            }
        }
        return false;
    }
}
Or
public class Solution {
    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;
    }
}

No comments:

Post a Comment