# LeetCode 217. Determine whether there are duplicate elements in the array

2022-04-29 16:19:09

 Come on, everybody , I like to break knowledge into small knowledge points by columns , Just say a piece of knowledge , Therefore, each article is short , I hope you don't mind . If necessary, you can check the column to see if there are articles to explain the knowledge points involved in this article , If you think it helps , I hope you will support me for the third time in a row .

### Article structure

217. There are duplicate elements

# Title Description

`````` Given an array of integers , Determine whether there are duplicate elements .
If a value exists, it appears at least twice in the array , The function returns  true . If every element in the array is different , Then return to  false .
``````

# Code implementation

## Method 1 double for

``````const nums = [1, 2, 3, 1];
const nums2 = [1, 2, 3];
//  Still shake hands
var containsDuplicate = function(nums) {

for (let i = 0; i < nums.length; i++) {

for (let j = i + 1; j < nums.length; j++) {

if (nums[i] == nums[j]) {

return true
}
}
}
return false
};
console.log(containsDuplicate(nums));
console.log(containsDuplicate(nums2));
``````

## Method 2Set+size

``````const nums = [1, 2, 3, 1];
const nums2 = [1, 2, 3];
var containsDuplicate = function(nums) {

// jsSet It has a de duplication effect
return new Set(nums).size == nums.length;
};
console.log(containsDuplicate(nums));
console.log(containsDuplicate(nums2));
``````

## Method 3Object+keys()+length

``````const nums = [1, 2, 3, 1];
const nums2 = [1, 2, 3];
var containsDuplicate = function(nums) {

// js Objects have unique properties
let obj = {
};
for (const iterator of nums) {

obj[iterator] = iterator;
}
return Object.keys(obj).length == nums.length;
};
console.log(containsDuplicate(nums));
console.log(containsDuplicate(nums2));
``````

## Method 4forEach()+indexof()+length

``````const nums = [1, 2, 3, 1];
const nums2 = [1, 2, 3];
var containsDuplicate = function(nums) {

//  Traverse to determine whether there are values in the new array , Do not add values repeatedly , Finally, judge whether the length of the new array is equal to that of the array
let arr = [];
nums.forEach(function(item) {

if (arr.indexOf(item) == -1) {

arr.push(item);
}
})
return arr.length == nums.length;
}
console.log(containsDuplicate(nums));
console.log(containsDuplicate(nums2));
``````

## Method 5sort()+for

``````const nums = [1, 2, 3, 1];
const nums2 = [1, 2, 3];
var containsDuplicate = function(nums) {

//  Prioritize , Then judge whether the adjacent items are equal
nums.sort();
for (let i = 0; i < nums.length - 1; i++) {

if (nums[i] == nums[i + 1]) {

return true;
}
}
return false;
};
console.log(containsDuplicate(nums));
console.log(containsDuplicate(nums2));
`````` 