442. Find All Duplicates in an Array
- Find All Duplicates in an Array python solution
题目描述
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?

解析
因为题目中要求在O(n)的运行时间,所以没有使用counter
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
ans=[]
count={}
for j in nums:
if j in count:
ans.append(j)
else:
count[j]=1
return ans
本文介绍了一种在给定整数数组中查找所有出现两次的元素的Python算法。该算法能在O(n)运行时间内完成任务,且不使用额外的空间。通过遍历数组并检查每个元素是否已经出现过,来实现这一目标。
365





