剑指offer-50.数组中重复的数字-python

50.数组中重复的数字

题目描述

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

记录

方法一:
字典

# -*- coding:utf-8 -*-
class Solution:
    # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
    # 函数返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        d = {}
        for i in numbers:
                if i not in d:
                    d[i] = 1
                else:
                    d[i] += 1
        for k,v in d.items():
            if v > 1:
                duplication[0] = k
                return True
        return False

方法二:
因为数组长度为n, 整数范围为0~n-1, 所以我们可以直接用这个数组来标记已经出现过的数, 如果再次在某次标记的时候又第二遇到, 那肯定就是有重复了 。

# -*- coding:utf-8 -*-
class Solution:
    # 这里要特别注意~找到任意重复的一个值并赋值到duplication[0]
    # 函数返回True/False
    def duplicate(self, numbers, duplication):
        # write code here
        cur = 0        
        while cur < len(numbers):            
            if numbers[cur] == cur:                
                cur += 1                
                continue                             
            if numbers[cur] == numbers[numbers[cur]]:                
                duplication[0] = numbers[cur]                
                return True                                  
            temp = numbers[cur]            
            numbers[cur] = numbers[numbers[cur]]            
            numbers[temp] = temp        
        return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值