标签:dup list mit https count exce ever ict 最快
最近学习python,在山东理工大学的oj上刷题(487-3279),但是才做到第二个题就老是TLE(Time Limit Exceeded),自己本机执行示例明明可以的,但是一提交就超时,后来发现题目中有个(up to 100,000),意思就是最大有10万条数据,那就在本地模拟一下,我去,瞬间让我感觉不对,本来应该很快执行结束的却花了我3分多钟,怪不得超时呢,后来研究了下,改进了下代码(仍有进步空间,我看到ac的最快用时600ms),使用了字典,执行时间在1秒左右了,提交终于通过了,那个激动啊??。
代码如下,供和我一样遇到问题的同学参考,希望少走点弯路
# -*- coding: UTF-8 -*-
# 输入的电话号码个数
num = int(input());
# 最多十万个
if num >= 100000:
num = 100000;
# 电话号码
input_array = [];
# 已输入的个数
flag = 0;
# 处理之后的电话
phone_array = [];
# 重复的电话和数量字典
phone_repeat_dict = {};
while (flag < num):
# 存储所有输入的电话
input_array.append(input());
flag += 1;
for tmp in input_array:
# 替换中横线
if '-' in tmp:
tmp = tmp.replace('-', '');
phone = "";
times = 0;
# 注意下面的数字必须加引号,因为这是字符
for t in tmp:
if t == "A" or t == "B" or t == "C":
phone += "2";
elif t == "D" or t == "E" or t == "F":
phone += "3";
elif t == "G" or t == "H" or t == "I":
phone += "4";
elif t == "J" or t == "K" or t == "L":
phone += "5";
elif t == "M" or t == "N" or t == "O":
phone += "6";
elif t == "P" or t == "R" or t == "S":
phone += "7";
elif t == "T" or t == "U" or t == "V":
phone += "8";
elif t == "W" or t == "X" or t == "Y":
phone += "9";
else:
phone += t;
# 插入横线
if times == 2:
phone += "-";
times += 1;
phone_array.append(phone);
# 没有方插入
if phone not in phone_repeat_dict.keys():
phone_repeat_dict[phone] = 1;
else:
phone_repeat_dict[phone] += 1;
# 没有重复的则输出 No duplicates.
times = 0;
# 转为list
phone_last_array = list(phone_repeat_dict.keys());
# 对结果要正序排序
phone_last_array.sort(reverse = False);
for i in phone_last_array:
phone_count = phone_repeat_dict[i];
if phone_count >= 2:
print(i + " " + str(phone_count));
times += 1;
# 次数等于0表示没有重复的
if times == 0:
print("No duplicates.");
【python3】OJ 1001 487-3279 Time Limit Exceeded
标签:dup list mit https count exce ever ict 最快
原文地址:https://www.cnblogs.com/lantor/p/11644250.html