Day1 数组中重复的数字【数组】

题目:
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

思路:
数组nums长度为n,value在 0~n-1的范围内。
创建新数组count,其下标在 0~n-1的范围内。
数组count的下标为 数组nums中的元素i,数组count的value为数组nums中元素i出现的次数
遍历数组nums,元素i每出现一次,count[i]就加1,当count[i]大于1时,终止循环,输出此时的i,即为数组中任意重复的数字值。

代码:

class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        count=[0]*len(nums)#创建新数组count,长度与nums相等,初始value均为0.[0]*2=[0,0]
        for i in nums:
            count[i]+=1
            if count[i]>1:
                return i

此前代码:
时间复杂度O(n^2),超过时间限制

class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        for i in nums:
            count=0
            for j in nums:
                if i==j:
                    count+=1
                if count==2:
                    return i

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_47128888/article/details/112427131