PAT 1054 The Dominant Color python解法

该博客介绍了如何解决PAT 1054问题,即在给定分辨率的图像中找到绝对主导颜色。博主首先解释了原始解法,通过建立数字及其出现次数的字典来寻找最常见的颜色,但这种方法在某些测试用例中导致超时。随后,博主提出了一个优化的解决方案,使用计数变量`count`来跟踪当前主导颜色的出现,当遇到不同颜色时减少计数,直到计数归零时更新主导颜色。这种方法能够有效提高效率,找出图像中占比超过一半的主导颜色。

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

1054 The Dominant Color (20 分)
Behind the scenes in the computer’s memory, color is always talked about as a series of 24 bits of information for each pixel. In an image, the color with the largest proportional area is called the dominant color. A strictly dominant color takes more than half of the total area. Now given an image of resolution M by N (for example, 800×600), you are supposed to point out the strictly dominant color.

Input Specification:
Each input file contains one test case. For each case, the first line contains 2 positive numbers: M (≤800) and N (≤600) which are the resolutions of the image. Then N lines follow, each contains M digital colors in the range [0,2^​24​​ ). It is guaranteed that the strictly dominant color exists for each input image. All the numbers in a line are separated by a space.

Output Specification:
For each test case, simply print the dominant color in a line.

Sample Input:
5 3
0 0 255 16777215 24
24 24 0 0 24
24 0 24 24 24
Sample Output:
24

解题思路:建立一个字典,键是数字,值是数字出现的次数。对每个数作如下判断,如果该数在字典里,则将该数对应的值加1,否则,添加一个键值对到字典中,键是该数字,值为1。全部数字判断完成后,只需输出字典中值最大对应的键,即所求。然而,这段代码有一个问题,在2号测试点运行超时。

d={}
col,row = map(int, input().split())
for i in range(row):
    l = list(input().split())
    for j in l:
        if j in d:
            d[j] = d[j]+1
        else:
            d[j] = 1
dominant = max(d,key=d.get)
print(dominant)

新解法: the dominant color肯定是大于总数的一半,可以用一个count计数,开始扫描输入数据,如果dominant和数据中元素相同,将count+1,如果不同将count-1,如果count==0,则更换dominant为当前元素,扫描完成后,dominant即为所求。

col,row = map(int, input().split())
l = []
dominant = 0
count = 0
for i in range(row):
    l = list(input().split())
    for i in l:
        if count == 0:       
            dominant = i
            count += 1
        if dominant == i:
            count += 1
        else:
            count -= 1
print(dominant)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

D_ry

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

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

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

打赏作者

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

抵扣说明:

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

余额充值