题目
解法:
题目的关键在于nums of length n where all the integers of nums are in the range [1, n],所以可以用nums本身来作为hashmap。那就要通过改变nums来达到这个目的,但是在改变的同时又能获取原本的nums信息,那就只有通过改变某个数字的符号
具体做法是:把每个数字作为索引,将这个数字代表的索引位置的数字改变符号,这样下次再碰到这个数字就能知道是否出现过,而且被改变符号的数字可以通过绝对值得到原本的数字
class Solution:
def findDuplicates(self, nums: List[int]) -> List[int]:
ans = []
for num in nums:
if nums[abs(num)-1] < 0:
ans.append(abs(num))
else:
nums[abs(num)-1] *= -1
return ans