Skip to content

Commit d57e81d

Browse files
authored
add a solution
1 parent ec031ca commit d57e81d

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

Kangli/Arrays/findAllDuplicates

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,23 @@ Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements
33
Find all the elements that appear twice in this array.
44
Could you do it without extra space and in O(n) runtime?
55
"""
6+
#O(1) extra space and O(n) time. Exploit the fact that the elements of nums all correspond to positions within nums and
7+
# find duplicates by marking visited indices.
8+
class Solution(object):
9+
def findDuplicates(self, nums):
10+
"""
11+
:type nums: List[int]
12+
:rtype: List[int]
13+
"""
14+
res =[]
15+
for n in nums:
16+
ind = abs(n) -1
17+
if nums[ind] < 0:
18+
res.append(abs(n))
19+
else:
20+
nums[ind] *= -1
21+
return res
22+
623
#accepted, first solution that came to mind but uses extra space
724
class Solution(object):
825
def findDuplicates(self, nums):

0 commit comments

Comments
 (0)