---
# System prepended metadata

title: 442. Find All Duplicates in an Array
tags: [Leetcode]

---

# 442. Find All Duplicates in an Array

## 題目敘述
![](https://i.imgur.com/aysUn8s.jpg)


題目意思:



## 初步想法
### 第一次看到
新建一個Object、array去統計每個數字出現次數，比如
1. Input: nums = [4,3,2,7,8,2,3,1]，輸出{1:1,2:2,3:2,4:1...}
2. 當nums.value>1，將nums.key放入output中輸出


## 解題

### 作法1 : Array、Object

```
var findDuplicates = function(nums) {
    let outP = []
    let keys ={}
    
    for(let i in nums){
        if(keys[nums[i]] == undefined){
            keys[nums[i]] = 1
        }
        else{
            keys[nums[i]] += 1
            if(keys[nums[i]] > 1) outP.push(nums[i])
        }
    } 
    return outP
};
```



### 最終結果

![](https://i.imgur.com/z7lOPOs.jpg)


### 作法2 : Array

```
var findDuplicates = function(nums) {
     let outP = []
     let key = []

     for(let i in nums){
       if(key[nums[i]-1] === undefined) key[nums[i]-1] = 1
       else key[nums[i]-1]++
       if(key[nums[i]-1] > 1) outP.push(nums[i])
     }
    return outP
};
```



### 最終結果

![](https://i.imgur.com/rZACyiL.jpg)

### 作法3: abs()

### 作法4:大風吹

###### tags: `Leetcode`