【查找算法(二分查找)】剑指 Offer 03. 数组中重复的数字

题目描述
找出数组中重复的数字。

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

示例
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3

题解1:用哈希表

class Solution:
    def findRepeatNumber(self, nums: List[int]) -> int:
        s = {
    
    }
        for i in nums:
            if i not in s:
                s[i] = 1 
            else:
                s[i] += 1
        for i in s.items():
            if i[1] > 1:
                return i[0]

题解2:用哈希集合,遍历一遍数组,如果集合里没有这个元素则加入集合,后续的遍历中,如果集合里有了这个元素,则说明重复了,返回即可

class Solution:
    def findRepeatNumber(self, nums: [int]) -> int:
        dic = set()
        for num in nums:
            if num in dic: return num
            dic.add(num)
        return -1 #返回-1这里可以删去,并没有用

猜你喜欢

转载自blog.csdn.net/Rolandxxx/article/details/128917056
今日推荐