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 66ed8fa

Browse files
📦 NEW: Remove duplicates from array Solved
1 parent c7d153a commit 66ed8fa

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Remove duplicates from array.
3+
*
4+
* @param {number[]} nums
5+
*
6+
* @return {number}
7+
*/
8+
var removeDuplicates = function(nums) {
9+
const hashMap = {};
10+
let totalFound = 0;
11+
12+
for (let i = 0; i < nums.length; i++) {
13+
let num = nums[i];
14+
15+
if (!(num in hashMap)) {
16+
hashMap[num] = i;
17+
18+
// Store total found
19+
totalFound++;
20+
21+
// Modify the array
22+
nums[totalFound - 1] = num;
23+
}
24+
}
25+
26+
return totalFound;
27+
};
28+
29+
module.exports = removeDuplicates;
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const removeDuplicates = require("./index");
2+
3+
test("[1, 1, 2] array would result 2", () => {
4+
expect(removeDuplicates([1, 2])).toStrictEqual(2);
5+
});
6+
7+
test("[0,0,1,1,1,2,2,3,3,4] array would result 5", () => {
8+
expect(removeDuplicates([0, 1, 2, 3, 4])).toStrictEqual(5);
9+
});
10+
11+
// Test with array
12+
const nums = [1, 1, 2, 4, 4, 5]; // Input array
13+
let expectedNums = [1, 2, 4, 5, 4, 5]; // The expected answer with correct length
14+
const expectTotalFound = 4;
15+
16+
test("nums = [1, 1, 2, 4, 4, 5] array would result 4 with array [1, 2, 4, 5, 4, 5]", () => {
17+
expect(removeDuplicates(nums)).toStrictEqual(4);
18+
19+
// Test also the previous array
20+
expect(nums).toStrictEqual(expectedNums);
21+
});

0 commit comments

Comments
(0)

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