第一题是给一个字符串,然后按照次数和ascii码的顺序,循环输出。比如输入eeefffggh,由于ascii的大小,e
'efgh' + 'efg' + 'ef' = 'efghefgef'。字符串中可包含数字和大小写英文字母。
思路是先用dict统计个数,然后将所有可能出现的字符放在一个数组里,维护起来,
Whole = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E'
'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x',
'y','z']
在dict中没有的就直接删除,然后再输出。有的话,那么将字典中的该字符的个数-1。直到字典中所有字符的个数均为0。
然而AC了77.78%,然后报超时,应该是算法复杂度太高吧。
#coding=utf8
x = raw_input()
def Not_Null(dic): #根据字典中所有键值的和是否为0,判断dict是否为空
sum = 0
for i in dic.values():
sum += i
if sum !=0: return True
else:
return False
leng = len(x)
dic = {}
for i in range(leng):
if x[i] not in dic:
dic[x[i]] =1
else:
dic[x[i]] +=1
Whole = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E'
'F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x',
'y','z']
res = ''
to_remove=[]
while (Not_Null(dic)):
for cha in Whole:
if cha not in dic or dic[cha] == 0:
to_remove.append(cha)
else:
dic[cha] -=1
for d in to_remove:
Whole.remove(d)
for cha in Whole:
res += cha
to_remove = []
print res
第二题是给一个数组,每个数字代表从数字的坐标的位置最多能前进的位数(比如[2,a,b],则从这里开始,可以走1步到a,也可以走两步到b),求到数组的末端所需要的最少的步数。
如:[2,3,2,1,2,1,5],最短的步骤是 2->2->2->5,或者2->3->2->5,都需要3步,所以输出3。
这一题用的是DFS回溯法写的,AC了。在开始做题的时候,想到可以从后往前思考, 应该是动态规划的思想,但没想出来。幸亏数组没有太长导致溢出。
#coding=utf8
N = int(raw_input())
num = []
for i in range(N):
num.append(int(raw_input()))
SUM = N - 1 #比如有7个数,则累加和是6
min_count = 9999999 #在dfs中被当做全局变量。
count = 0
def dfs(SUM,num,index,step):
global min_count
if SUM == 0:
if step <= min_count:
min_count = step #终止并赋值
return
if SUM < 0:
return #减多了,直接返回
else:
x = num[index]
for i in range(1,x+1):
if index + i <= len(num)-1: #判断是否直接越界。
SUM -= i
index += i
step += 1
dfs(SUM,num,index,step)
SUM += i #在每一轮循环后,要退回去,回溯法!
index -= i
step -= 1
dfs(SUM,num,0,0)
print min_count
第三题,大数相乘。今年华为3.22机试的原题。。由于今天刚刚刷过,所以电脑里有源代码,就直接复制了。然后AC
参考的是 https://blog..net/u010983881/article/details/77503519 的方法二
num1 = raw_input()
num2 = raw_input()
sign1 = 1
sign2 = 1
if num1[0] == '-':
sign1 = -1
num1 = num1[1:]
if num2[0] == '-':
sign2 = -1
num2 = num2[1:]
leng1 = len(num1)
leng2 = len(num2)
ans =[0 for i in range(leng1 + leng2)]
for i in range(leng1):
for j in range(leng2):
mul = int(num1[i]) * int(num2[j])
ans[i+j+1] += mul
for i in range(leng1+ leng2 - 1, -1, -1):
if ans[i] >= 10:
ans[i-1] += ans[i] / 10
ans[i] = ans[i] % 10
res = ""
for bit in ans:
res += str(bit)
num_res = int(res) * sign1 * sign2
print str(int(num_res))