老卫带你学---剑指offer刷题系列(50.数组中重复的数字)

50.数组中重复的数字

问题:

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

解决:

思想:

计数问题,立马推,使用字典或者计数器

python代码:

# -*- coding:utf-8 -*-
from collections import Counter
class Solution:
    # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
    # 函数返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        flag=False
        c=Counter(numbers)
        for k,v in c.items():
            if(v>1):
                duplication[0]=k
                flag=True
                break
        return flag
发布了166 篇原创文章 · 获赞 30 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/yixieling4397/article/details/105070840