题目:
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]
解题思路:
由于题目要求不能使用额外的空间,又数组中的数字为1到n,故可以利用数组本身来记录一个数字是否出现两次,通过将数组数字作为下标将对应数组位置的数字取反变为负数,若出现了两次,则再次取反变为正数,即可判断该数字是否出现两次。
代码:
class Solution: def findDuplicates(self, nums): re = [] for i in range(len(nums)): absnums = nums[i] if absnums < 0: absnums = -absnums nums[absnums-1] = -nums[absnums-1] if nums[absnums-1] > 0: re.append(absnums) return re