I scan the array once while keeping a set of numbers I have already seen. Whenever I encounter a number that is already in the set, it must be one of the sneaky repeated numbers, so I add it to the result list. Since there are exactly two repeats, I stop once I found both.
class Solution:
def getSneakyNumbers(self, nums: List[int]) -> List[int]:
seen = set()
res = []
for x in nums:
if x in seen:
res.append(x)
if len(res) == 2:
break
else:
seen.add(x)
return res- Time: O(n)
- Space: O(n)