牛客【2021】第三次校招模拟笔试(编程题部分)
牛客【2021】第三次校招模拟笔试(编程题部分)
第一题:牛牛A+B
牛妹在黑板上写下两个正整数a,b。她想让牛牛帮忙计算“A+B”,牛牛一听,这还不简单?但是牛妹说:此“A+B”非彼“A+B”,而是要先把a重复b次,把b重复a次,再计算刚刚得到的这两个数字的和。
这下可难到了牛牛,请帮助牛牛解决这个问题吧!
现在给你a,b返回牛妹要求的正确答案。
思路:转换为字符串
class Solution: def NNAplusB(self , a , b ): a,b = int(str(a)*b),int(str(b)*a) return a + b
第二题:牛妹的LIS
思路:找规律
首先因为n<=10^100000次方,所以就别写for循环了,更别写双层了,一定超时。
重新思考,出现一个数,要求子序列中的最大值。所以低位一定是“9”最好。 首先n<10,就是n本身
n刚好就是最大的子序列的最大值,例如:199,“199” = 19 n比最大子序列的最大值大,例如200,子序列最大“199” = 19
class Solution: def NS_LIS(self , n ): # write code here if len(n) == 1: return int(n) res = n[0] + "9"*(len(n)-1) if int(res)>int(n)and res[0]!="1": res = str(int(n[0])-1) + res[1::] elif int(res)>int(n)and res[0]=="1": res = res[1::] s = 0 for i in res: s += int(i) return s
第三题:魔法师牛牛
思路:排序+前缀和
AC 58.33%
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param h int整型一维数组 # @return int整型一维数组 # class Solution: def Magical_NN(self , h ): # write code here dic= { } st = sorted(h) lst = [st[0]] for i in st[1::]: lst.append(lst[-1]+i) for i in range(len(h)): if h[i] not in dic: dic[h[i]] = (st.index(h[i])+1)*h[i] - lst[st.index(h[i])] - (len(st)-(st.index(h[i])+1))*h[i] + lst[-1]-lst[st.index(h[i])] h[i] = dic[h[i]] return h
上一篇:
Java基础知识总结(2021版)