其他分享
首页 > 其他分享> > leetcode刷题—442. 数组中重复的数据

leetcode刷题—442. 数组中重复的数据

作者:互联网

题目

题目

方法1

在这里插入图片描述

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

方法2

https://leetcode-cn.com/problems/find-all-duplicates-in-an-array/solution/442li-yong-chu-li-by-strange-williamsonv-7cey/

class Solution(object):
    def findDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        n = len(nums)
        res = []
        for i in range(n):
            ind = (nums[i]-1)%n
            nums[ind]+=n
        for i in range(n):
            if nums[i]>2*n:
                res.append(i+1)
        return res

标签:findDuplicates,nums,int,442,List,range,res,leetcode,刷题
来源: https://blog.csdn.net/weixin_48229346/article/details/121054202