蘑菇街2016招聘笔试(最大间隔)

本文探讨了一种算法,用于解决给定递增序列中删除一个元素后剩余序列最大间隔的最小值问题,并提供了详细的代码实现及分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

给定一个递增序列,a1 <a2 <…<an 。

定义这个序列的最大间隔为d=max{ai+1 – ai }(1≤i<n)

现在要从a2 ,a3 ..an-1 中删除一个元素。问剩余序列的最大间隔最小是多少?

输入描述:

第一行,一个正整数n(1<=n<=100),序列长度;

接下来n个小于1000的正整数,表示一个递增序列。

输出描述:

输出答案。

输入例子:

5

1 2 3 7 8

输出例子:

4

分析:

这个题是要求删除一个元素后,剩余序列的最大间隔的最小值,注意逻辑观念是最大间隔,然后是最大间隔的最小值,那么我们就可以先求最大间隔,把他们放到列表里,然后再求这个最大间隔列表里的最小值

话不多少,代码和分析如下:

#-*-coding:UTF-8-*-
n = int(raw_input())#输入n为序列的元素个数
s = raw_input().split()
s = map(int,s)#将字符串转化成整数串
lens = len(s)#lens为外部大循环变量
a = []#a是每次去掉一个元素时其余相邻元素间差值的列表
b = []#b就是每次a中最大数的列表集合
for i in range(lens-1):#请注意为什么不直接输入len(s)呢,这是因为s
    #z最后要还原回原始序列以便下一次删除另外的元素
    print 'The %dth time we remove the %dth number of the list:' % ((i+1), (i+2)) ,s[i+1]
    c = s[i+1]#c是当前循环所要删除的元素,之后要插入回它原来的位置
    s.remove(s[i+1])#将当前元素删除
    print 'now the new list is:',s#显示当前循环时删除元素后的序列
    for j in range(len(s)-1):#这个循环是计算新序列下相邻元素间的差值
        a.append(s[j+1]-s[j])
    b.append(max(a))#然后我们把相邻元素间的差值序列中最大的那个值放到
    #最大差值列表b里面
    print 'the list of the spaces among the adjoining elements is:',a
    s.insert(i+1,c)#等以上操作结束后,我们把删除的元素再给它加进去
    #有个更简便的方法就是复制初始序列,当然代码会少一两句
    #print s
    print 'and the max space is:',max(a),'\n'
    a = []#这个时候一定要清空间隔序列,因为下一次循环条件下
    #相邻元素间的差值肯定又会不一样

print 'above all ,the max space list is:',b
print 'now we choose the minimum element in b is:',min(b)

输出结果展示:

5
1 2 3 7 8
The 1th time we remove the 2th number of the list: 2
now the new list is: [1, 3, 7, 8]
the list of the spaces among the adjoining elements is: [2, 4, 1]
and the max space is: 4

The 2th time we remove the 3th number of the list: 3
now the new list is: [1, 2, 7, 8]
the list of the spaces among the adjoining elements is: [1, 5, 1]
and the max space is: 5

The 3th time we remove the 4th number of the list: 7
now the new list is: [1, 2, 3, 8]
the list of the spaces among the adjoining elements is: [1, 1, 5]
and the max space is: 5

The 4th time we remove the 5th number of the list: 8
now the new list is: [1, 2, 3, 7]
the list of the spaces among the adjoining elements is: [1, 1, 4]
and the max space is: 4

above all ,the max space list is: [4, 5, 5, 4]
now we choose the minimum element in b is: 4


遇到的困难和感悟:

有些题目看似简单其实暗藏玄机,就拿这道题来说,最大间隔的最小值比较绕口,让我们先确定好思路

另外就是在程序中,注意主循环一定不能以len(s)作为循环范围,因为s每次要还原

还有就是子循环要注意不能和主循环的变量一样,因为什么呢?

因为我们在插入的时候它的变量是不能变的,举个例子,第一次循环它先去掉的是第二元素,在列表中它的下标为1,就是‘2’,倘若我们子循环变量也是i的话,子循环结束后,i就变成了多少?没错就是3了,那么这个时候把删除掉的2通过函数

s.insert(i+1,c)
就插入到了尾部,就成了[1,3,7,8,2]了,但是我们原来的序列是[1,2,3,7,8]啦!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值