contains duplicate

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.

代码一(23ms):

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> s = new HashSet<Integer>();
        for (int n : nums) {
            if (s.contains(n)) {
                return true;
            } else {
                s.add(n);
            }
        }
        return false;
    }
}

代码二(19ms):

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

代码三(7ms):

public class Solution {
    public boolean containsDuplicate(int[] nums) {
        if(nums.length == 0 || nums.length == 1)
            return false;
        Arrays.sort(nums);
        int p = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int n = nums[i];
            if (n == p) {
                return true;
            }
            p = n;
        }
        return false;
    }
}