Question

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.

Example 1:

Input: [1,2,3,1]
Output: true

Thinking:

  • Method:
    • 使用hashset.O(n)
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for(int n : nums){
            if(set.contains(n)) return true;
            set.add(n);
        }
        return false;
    }
}

二刷

  1. Sort the array first and traverse the array from the second index.
  2. check if current number equals the previous one, if equal, return true, else false;
    class Solution {
     public boolean containsDuplicate(int[] nums) {
         Arrays.sort(nums);
         for(int i = 1; i < nums.length; i++){
             if(nums[i] == nums[i - 1]) return true;
         }
         return false;
     }
    }