-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
problem: 0442 find all duplicates in an array
- Loading branch information
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
54 changes: 54 additions & 0 deletions
54
0442 Find All Duplicates in an Array/0442 Find All Duplicates in an Array.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
# 0442. Find All Duplicates in an Array | ||
|
||
- Difficulty: medium | ||
- Link: https://leetcode.com/problems/find-all-duplicates-in-an-array | ||
- Topics: Array-String | ||
|
||
# Clarification | ||
|
||
1. Check the inputs and outputs | ||
- INPUT: List[int] | ||
- OUTPUT: List[int] | ||
2. Check the main goal | ||
- return the duplicate numbers | ||
- time complexity $O(n)$ | ||
- space complexity $O(1)$ | ||
|
||
# Naive Solution | ||
|
||
### Thought Process | ||
|
||
1. iterate the array | ||
1. consider the element as the index | ||
2. find the corresponding element | ||
1. is already negative → duplicate | ||
2. times it with negative | ||
- Implement | ||
|
||
```python | ||
class Solution: | ||
def findDuplicates(self, nums: List[int]) -> List[int]: | ||
""" | ||
1. iterate the array | ||
a. consider the element as the index | ||
b. find the corresponding element | ||
i. is already negative → duplicate | ||
ii. times it with negative | ||
""" | ||
result = [] | ||
for num in nums: | ||
absNum = abs(num) | ||
if nums[absNum - 1] < 0: | ||
result.append(absNum) | ||
nums[absNum - 1] *= (-1) | ||
return result | ||
``` | ||
|
||
|
||
### Complexity | ||
|
||
- Time complexity: $O(n)$ | ||
|
||
 | ||
|
||
- Space complexity:$O(1)$ |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.