PAT 1041 Be Unique python解法

这是一个关于PAT(编程能力测试)1041题目的解题报告,问题涉及寻找唯一数。给定一组不超过105个的数,目标是找出第一个出现且唯一的数。若所有数都重复,则输出None。文章描述了两种Python解题思路,一种使用列表,但可能导致超时;另一种利用字典记录次数,能更高效地找到唯一数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1041 Be Unique (20 分)
Being unique is so important to people on Mars that even their lottery is designed in a unique way. The rule of winning is simple: one bets on a number chosen from [1,10​4]. The first one who bets on a unique number wins. For example, if there are 7 people betting on { 5 31 5 88 67 88 17 }, then the second one who bets on 31 wins.

Input Specification:
Each input file contains one test case. Each case contains a line which begins with a positive integer N (≤105​​ ) and then followed by N bets. The numbers are separated by a space.

Output Specification:
For each test case, print the winning number in a line. If there is no winner, print None instead.

Sample Input 1:
7 5 31 5 88 67 88 17
Sample Output 1:
31
Sample Input 2:
5 888 666 666 888 888
Sample Output 2:
None

解题思路:题意是找第一个与其他数不相同的数,输入的一行数据中,第一个数n是一共有几个数,后面跟着n个数。
第一个思路:建立两个列表,unique储存不相同的数,same存储去掉重复值之后的数,对输入l进行循环判断,如果l中元素在unique中,则将unique中该数删除,如果l中元素不在same中,则将该元素添加到same和unique中,循环结束后,如果unique中有元素,则输出第一个元素,如果为空,则输出None。此方法在2个测试点中超时。

#2个测试点运行超时
l = list(map(int,input().split()))
#l = [5, 888, 666, 666, 888, 888]
#l = [7, 5, 31, 5, 88, 67, 88, 17]
d = {}
for i in l[1:]:
    if i not in d.keys():
        d[i] = 1
    else:
        d[i] += 1
out = 0
for i in l[1:]:
    if i in d.keys() and d[i] == 1:
        out = i
        break
if out:
    print(out)
else:
    print('None')

第二个思路:建立一个字典d,对输入l进行循环判断,如果l中元素不在字典d中,则添加到字典d中,键为该元素,值为1,如果在字典d中,则将对应值加1。再对列表进行循环判断,找到第一个在字典d中的元素后跳出循环并将该元素保存到out中。out的初始值为0,因为题目所给的数据在[1,10​4],0不在其中。最后判断out是否为0,如果为0,则输出None,否则输出out。

l = list(map(int,input().split()))
#l = [5, 888, 666, 666, 888, 888]
#l = [7, 5, 31, 5, 88, 67, 88, 17]
d = {}
for i in l[1:]:
    if i not in d.keys():
        d[i] = 1
    else:
        d[i] += 1
out = 0
for i in l[1:]:
    if i in d.keys() and d[i] == 1:
        out = i
        break
if out:
    print(out)
else:
    print('None')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

D_ry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值