Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
The first solution is similar to 448: Find All Numbers Disappeared in an Array, The second solution uses hashmap.
- Move number to the position (number - 1)
class Solution:
def findDuplicates(self, nums: 'List[int]') -> 'List[int]':
res = []
i = 0
while i < len(nums):
if nums[i] != nums[nums[i]-1]:
temp= nums[i]
nums[i] = nums[temp-1]
nums[temp-1] = temp
else:
i += 1
for i in range(len(nums)):
if i+1 != nums[i]:
res.append(nums[i])
return res
- Hashmap
class Solution:
def findDuplicates(self, nums: 'List[int]') -> 'List[int]':
res = []
dic = {}
for num in nums:
if num in dic:
res.append(num)
else:
dic[num] = ''
return res