暴力解法

  1. /**
  2. * @param {number[]} nums
  3. * @return {number[]}
  4. */
  5. var findDuplicates = function(nums) {
  6. let arr =[]
  7. let result =[]
  8. nums.forEach(data=>{
  9. arr.includes(data) ? result.push(data) : arr.push(data)
  10. })
  11. return result
  12. };

image.png

哈希表

  1. /**
  2. * @param {number[]} nums
  3. * @return {number[]}
  4. */
  5. var findDuplicates = function(nums) {
  6. const map = new Map()
  7. const arr = []
  8. for(let i = 0; i < nums.length; i++) {
  9. if (map.has(nums[i])) {
  10. arr.push(nums[i])
  11. map.delete(nums[i])
  12. } else {
  13. map.set(nums[i])
  14. }
  15. }
  16. return arr
  17. };

image.png