21机试真题

This commit is contained in:
Sheldoer
2021-04-06 11:03:14 +08:00
parent 4666e4b2b0
commit 1bdcae9d3d
4 changed files with 80 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
'''
第一题题目:给定一个整数数组,找到每个元素的下一个比它的数,存在返回数组内,
其后没有比它大的数则返回None
'''
def find_next(L):
length=len(L)
res=[]
for i in range(length):
flag=0 #flag
for j in range(i+1,length):
if L[j]>L[i]:
res.append(L[j])
flag=1
break
if flag==0:
res.append(None)
return res
if __name__=='__main__':
L=[2,3,5]
L=[5,2,3]
print(find_next(L))

View File

@@ -0,0 +1,20 @@
'''
第三题题目:给定指定整数数组,找到数组中乘积最大的两个数字,
并以元组的形式返回这两个数字,并且这两个数字从小到大排序
'''
def find_pair(L):
length=len(L)
mxmul=L[0]*L[1]
indext=(L[0],L[1])
for i in range(length):
for j in range(i+1,length):
if L[i]*L[j]>=mxmul:
mxmul=L[i]*L[j]
indext=[L[i],L[j]]
return tuple(sorted(indext))
if __name__=='__main__':
#L=[1,-1,0]
L=[-10,-3,5,6,-2]
print(find_pair(L))

View File

@@ -0,0 +1,16 @@
'''
第二题题目:给定指定整数找到从1到该数的二进制表示中所有1的数目大于0的数字
存到返回数组中
例如15二进制表示为0b1111,
其中[1, 3, 5, 6, 7, 11, 13, 14, 15]二进制表示1的数目大于0的数目
'''
def find_number(n):
res=[]
for i in range(n+1):
s=bin(i)[2:] #remove '0b'
if s.count('1')>s.count('0'):
res.append(i)
return res
if __name__=='__main__':
print(find_number(15))

View File

@@ -0,0 +1,23 @@
'''
第四题题目:给定一些列集合的数组,从中找到所有数字的出现率高于出现一半的数字,
并以集合的形式返回该数字如果没有则返回None
'''
def find_major(L):
length=len(L)
lst=[]
res=set()
for i in L:
for j in list(i):
lst.append(j)
for i in set(lst):
if lst.count(i)>length/2:
res.add(i)
if len(res)>0:
return res
if __name__=='__main__':
L=[{1},{1,2},{1}]
#L=[{1},{2,3}]
print(find_major(L))