forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-all-duplicates-in-an-array.py
51 lines (44 loc) · 1.17 KB
/
find-all-duplicates-in-an-array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Time: O(n)
# Space: O(1)
class Solution(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = []
for i in nums:
if nums[abs(i)-1] < 0:
result.append(abs(i))
else:
nums[abs(i)-1] *= -1
return result
# Time: O(n)
# Space: O(1)
class Solution2(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = []
i = 0
while i < len(nums):
if nums[i] != nums[nums[i]-1]:
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
else:
i += 1
for i in xrange(len(nums)):
if i != nums[i]-1:
result.append(nums[i])
return result
# Time: O(n)
# Space: O(n), this doesn't satisfy the question
from collections import Counter
class Solution3(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return [elem for elem, count in Counter(nums).items() if count == 2]