> For the complete documentation index, see [llms.txt](https://emmaguo100.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://emmaguo100.gitbook.io/leetcode/02-02-2022-217.md).

# 02/02/2022 217

Brutal force two for loops and compare each elements

Time O(n^2)

Space O(1)

```
// Some code
class Solution { 
    public boolean containsDuplicate(int[] nums) { 
        for (int i = 0; i < nums.length; i++){ 
            for(int j = i + 1; j < nums.length; j++){ 
                if(nums[i] == nums[j]) return true; 
            } 
        } 
        return false; 
    } 
}
```

Method 2: sort the array and check if the adjacent elements have the same value.

Time O(nlogn)

Space O(1)

```
// Some code

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;
    }
}
```

Method: use hashset to add each elements, if it contains the element, return true. Otherwise return false;

Time O(n)

Space O(n)

```
// Some code
class Solution {
    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++){
            if(set.contains(nums[i])) return true;
            set.add(nums[i]);
        }
     return false;
    }
}
```
