如果差值不在字典中,就创建一个新的键值对;如果存在于字典中,就将相应的值加1。减少了一个遍历的使用
n = int(input())
num = list(map(int,input().split()))
result = {}
for i in range(n):
diff = abs(num[i]-i-1)
if diff in result:
result[diff] += 1 # 差值在字典的键中,就将相应的值加1
else:
result[diff] = 1 # 差值不在字典的键中,就创建一个新的键值对
# result = {2: 2, 3: 2, 5: 2}
result = list(result.items()) # result = [(2, 2), (3, 3), (5, 2), (1, 1)]
result.sort(reverse=True) # result = [(5, 2), (3, 3), (2, 2), (1, 1)]
for m in result:
if m[1] != 1: # 重复次数为2及以上才输出
print(*m,sep=' ')
上面是使用包含元组的列表进行排列,还可以使用值进行排列,对字典使用sorted()函数,就没有key部分了,只返回包含value部分的排序列表
res = sorted(result,reverse=True) # res = [5, 3, 2, 1] print(res) for m in res: if result[m] != 1: print(m,result[m])
测试点3超时。python效率太低,需要减少遍历的使用
n = int(input())
num = list(map(int,input().split()))
number = []
result = {}
for i in range(n):
diff = abs(num[i]-i-1)
number.append(diff)
for k in number:
if k not in result:
count = number.count(k)
if count != 1: # 重复次数为2及以上才写入输出字典
result[k] = count
result = list(result.items())
result.sort(reverse=True)
for m in result:
print(*m,sep=' ')