Skip to content

Commit 5656c93

Browse files
committed
Add solution #442
1 parent fc254d3 commit 5656c93

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
350|[Intersection of Two Arrays II](./0350-intersection-of-two-arrays-ii.js)|Easy|
5555
383|[Ransom Note](./0383-ransom-note.js)|Easy|
5656
387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy|
57+
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|
5758
448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy|
5859
451|[Sort Characters By Frequency](./0451-sort-characters-by-frequency.js)|Medium|
5960
459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy|
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 442. Find All Duplicates in an Array
3+
* https://leetcode.com/problems/find-all-duplicates-in-an-array/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer array nums of length n where all the integers of nums
7+
* are in the range [1, n] and each integer appears once or twice, return
8+
* an array of all the integers that appears twice.
9+
*
10+
* You must write an algorithm that runs in O(n) time and uses only constant
11+
* extra space.
12+
*/
13+
14+
/**
15+
* @param {number[]} nums
16+
* @return {number[]}
17+
*/
18+
var findDuplicates = function(nums) {
19+
const result = [];
20+
21+
nums.forEach((num, i) => {
22+
const key = Math.abs(num) - 1;
23+
if (nums[key] < 0) {
24+
result.push(Math.abs(num));
25+
} else {
26+
nums[key] *= -1;
27+
}
28+
});
29+
30+
return result;
31+
};

0 commit comments

Comments
 (0)