算法笔记——对数组统计并排序

1290天前 · 分享 · 507次阅读

华为OD机试第一题。

题目描述:

给一个数组,逗号隔开的,然后统计每个数字出现的次数,输出结果按大到小排序,次数相同的,按原来在数组里的左右顺序排。

解答:

这个题似乎是做过的,但是一时短路,只好用笨方法统计,手动排了下。

import sys 
for line in sys.stdin:
    nums = line.strip().split(",")
    res = []
    res2 = []
    for index, num in enumerate(nums):
        num = int(num)
        if num in res:
            res2[res.index(num)] += 1
        else:
            res.append(num)
            res2.append(1)
    length = len(res)
    _res = []
    for i in range(length):
        max_index = res2.index(max(res2))
        _ = res2.pop(max_index)
        _res.append(str(res.pop(max_index)))
    print(",".join(_res))
👍 0

none

最后修改于1290天前

评论

贴吧 狗头 原神 小黄脸
收起

贴吧

狗头

原神

小黄脸

目录

avatar

未末

迷失

126

文章数

275

评论数

7

分类