题解 | #H25 数据分类处理#
数据分类处理
https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
方法1-使用列表构建输出
s1 = input().split()[1:]
s2 = list(map(str, sorted(set(map(int, input().split()[1:])))))
ret = []
for num in s2:
tmp = []
for i, sub in enumerate(s1):
if num in sub:
tmp.extend([str(i), sub])
if tmp:
ret.extend([num, str(len(tmp) // 2)] + tmp)
print(str(len(ret)) + " " + " ".join(ret))
方法2-直接构建字符串
I = input().split()[1:]
R = list(map(str, sorted(map(int, set(input().split()[1:])))))
out = "" # 最终输出
total = 0 # 统计总计数
for r in R:
s = ''
count = 0 # 统计I中包含r的元素个数
for i, v in enumerate(I):
if r in v:
s += str(i) + " " + v + " "
total += 2
count += 1
if count:
s = r + " " + str(count) + " " + s
total += 2
out += s
print((str(total) + " " + out).strip())
方法3-使用字典
I = input().split()[1:]
R = sorted(map(int, set(input().split()[1:])))
# 构建字典
dic = {}
for r in R:
for idx, item in enumerate(I):
if str(r) in item:
if r not in dic:
dic[r] = [(str(idx), item)]
else:
dic[r].append((str(idx), item))
# 计算total
total = len(dic) * 2 + sum(len(v) for v in dic.values()) * 2
# 构建输出列表
ret = []
for k, v in sorted(dic.items()):
count = str(len(v))
ret.extend([str(k), count] + [elem for pair in v for elem in pair])
# 打印结果
print(f'{total} ' + ' '.join(ret))
【牛客站内】华为机试题解 文章被收录于专栏
【牛客站内】 分享个人刷题的思路和解法


查看9道真题和解析