CCF 201612-1 中间数 python 满分

56 篇文章 4 订阅

题目叙述

问题描述:略

输入格式:略

输出格式:略

样例

样例输入
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. 中间数在最中间附近产生;
  2. 只需要取出中间(±1)附近的数,验证就好了;
  3. 奇数去3个;
  4. 偶数取4个;
  5. 利用+ -1之和判断;
  6. 用flag标记是否找到。

大佬版本

  1. eval(<字符串>) 能够以Python表达式的方式解析并执行字符串,并将返回结果输出;
  2. eval()函数都将其解释为int类型;
  3. //进行暴力整除
  4. 巧妙利用索引从0开始
  5. 计算相同数的数量
  6. 用长度和索引去比较
    实在是高高高

满分代码

笨办法版本:穷举法

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 满分代码目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值