442. 数组中重复的数据

题目描述:给定一个整数数组 a,其中1 ≤ a[i] ≤ n (n为数组长度), 其中有些元素出现两次而其他元素出现一次。找到所有出现两次的元素。你可以不用到任何额外空间并在O(n)时间复杂度内解决这个问题吗?

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[2,3]

思路1:这个题目开头暗示了n的范围,所以可以加以利用,将元素转换成数组的索引并对应的将该处的元素乘以-1;若数组索引对应元素的位置本身就是负数,则表示已经对应过一次;在结果列表里增加该索引的正数就行;

class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        res = []
        for i in range(len(nums)):
            loc = abs(nums[i]) - 1
            if nums[loc] < 0:
                res.append(loc + 1)
            nums[loc] = -nums[loc]
        return res

思路2:排序

通过索引号排序,比如数字4放到索引3的位置,最后找排序后数组,与索引号没有相差1便是重复元素

class Solution:
    def findDuplicates(self, nums: List[int]) -> List[int]:
        res = []
        for i in range(len(nums)):
            while nums[nums[i] - 1] != nums[i]:
                tmp = nums[i]
                loc = nums[i] - 1
                nums[i] = nums[nums[i] - 1]
                nums[loc] = tmp
        for idx, val in enumerate(nums, 1):
            if val != idx:
                res.append(val)
        return res

测试用例:
[4,3,2,7,6,2,3]

中间结果:
[7, 3, 2, 4, 6, 2, 3]
[3, 3, 2, 4, 6, 2, 7]
[2, 3, 3, 4, 6, 2, 7]
[3, 2, 3, 4, 6, 2, 7]
[3, 2, 3, 4, 2, 6, 7]

最后输出:
[3,2]

  

原文地址:https://www.cnblogs.com/USTC-ZCC/p/12881024.html