CCF 201612-1 中间数 python 满分
题目叙述
问题描述:略
输入格式:略
输出格式:略
样例
样例输入
6
2 6 5 6 3 5
样例输出
5
样例说明
比5小的数有2个,比5大的数也有2个。
样例输入
4
3 4 6 7
样例输出
-1
样例说明
在序列中的4个数都不满足中间数的定义。
样例输入
5
3 4 6 6 7
样例输出
-1
样例说明
在序列中的5个数都不满足中间数的定义。
满分证明
解题思路
笨办法版本:穷举法
穷举遍历(时间长)
升级版本:只验证中间的
- 中间数在最中间附近产生;
- 只需要取出中间(±1)附近的数,验证就好了;
- 奇数去3个;
- 偶数取4个;
- 利用+ -1之和判断;
- 用flag标记是否找到。
大佬版本
- eval(<字符串>) 能够以Python表达式的方式解析并执行字符串,并将返回结果输出;
- eval()函数都将其解释为int类型;
- //进行暴力整除
- 巧妙利用索引从0开始
- 计算相同数的数量
- 用长度和索引去比较
实在是高高高
满分代码
笨办法版本:穷举法
n = int(input())
a = list(map(int,input().split()))
error = False #用来判断是否输出-1
for i in range(n):
big = 0
small = 0
for j in range(n):
if(i == j):
continue
if(a[i] > a[j]):
small += 1
elif(a[i] < a[j]):
big += 1
if (big == small):
error = True
print(a[i])
break
if error == False:
print(-1)
升级版本:只验证中间的
n = int(input())
ps = list(map(int, input().split()))
ps.sort()
nps = list(set(ps))
flag = [0, 0, 0, 0]
lop = -1
if len(ps) % 2 != 0:
flag[0] = ps[int((len(ps)) / 2)]
ind = nps.index(flag[0])
if ind + 1 < len(nps):
flag[1] = nps[ind + 1]
if ind - 1 >= 0:
flag[2] = nps[ind - 1]
else:
flag[0] = ps[int((len(ps) - 1) / 2)]
flag[1] = ps[int((len(ps) - 1) / 2) + 1]
ind = nps.index(flag[0])
if ind - 1 >= 0:
flag[2] = nps[ind - 1]
if ind + 2 < len(nps):
flag[3] = nps[ind + 2]
for o in range(4):
ss = []
for i in range(len(ps)):
if flag[o] > ps[i]:
ss.append(1)
elif flag[o] < ps[i]:
ss.append(-1)
elif flag[o] == ps[i]:
ss.append(0)
if sum(ss) == 0:
lop = 1
print(flag[o])
break
if lop == -1:
print(-1)
大佬版本
n=eval(input())
strings=input().split()
list1=[eval(x) for x in strings]
list1.sort()
len2=len(list1)
len1=len2//2
temp=list1[len1]
count1=list1.count(temp)
index1=list1.index(temp)
index2=index1+count1
if index1==len2-index2:
print(temp)
else:
print(-1)
感谢及参考博文
部分内容参考以下链接,这里表示感谢 Thanks♪(・ω・)ノ
参考博文1 CCF 201612-1 中间数(python 满分小白版)
https://blog.csdn.net/m0_45057667/article/details/108419686
参考博文2 CCF–201612-1–中间数—python 100分(大佬版)
https://blog.csdn.net/weixin_41508608/article/details/89424489
需者自取传送门(∩ᄑ_ᄑ)⊃━☆【CCF 2013-2021】本博主整理历年至少前两题 python 满分代码目录