|
| 1 | +// Duplicate Numbers |
| 2 | +// Write a function that takes in an array of numbers and returns if there are any duplicate numbers or not |
| 3 | + |
| 4 | +// on a long array this method could be inefficient |
| 5 | +const containsDupNums = numArr => { |
| 6 | + let isDup = false |
| 7 | + numArr.forEach((num, i, array) => { |
| 8 | + // check if index of current number is the same if searched from the end of the array (it didn't find a duplicate along the way at a different index) |
| 9 | + if (i !== array.lastIndexOf(num)) { |
| 10 | + isDup = true |
| 11 | + } |
| 12 | + }) |
| 13 | + return isDup |
| 14 | +} |
| 15 | + |
| 16 | +console.log(containsDupNums([1, 2, 3, 1])) |
| 17 | +console.log(containsDupNums([1, 2, 3])) |
| 18 | +console.log(containsDupNums([0, 4, 5, 0, 3, 6])) |
| 19 | + |
| 20 | +// |
| 21 | +// |
| 22 | +// using sort then find on a very long array could be more efficient |
| 23 | +const containsDubNumsSort = numArr => { |
| 24 | + let dupNum = numArr |
| 25 | + .sort((num1, num2) => { |
| 26 | + return num1 - num2 |
| 27 | + }) |
| 28 | + .find((num, i, array) => { |
| 29 | + if (i < array.length - 1) { |
| 30 | + // go through the sorted array and check if current number is equal to its following number in the array |
| 31 | + return num === array[i + 1] |
| 32 | + } |
| 33 | + }) |
| 34 | + // if dupNum is a number, including 0 or negative, return true |
| 35 | + return dupNum !== undefined ? true : false |
| 36 | +} |
| 37 | + |
| 38 | +console.log(containsDubNumsSort([1, 2, 3, 1])) |
| 39 | +console.log(containsDubNumsSort([1, 2, 3])) |
| 40 | +console.log(containsDubNumsSort([0, 4, 5, 0, 3, 6])) |
0 commit comments