Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6ec8ae6

Browse files
Duplicate Numbers
1 parent 7e61724 commit 6ec8ae6

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎12_Duplicate-Numbers/index.js‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /