PAT 1054 The Dominant Color python解法

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)

你可能感兴趣的:(python,用Python刷PAT,(Advanced,Level),Practice)