拼多多算法岗100 100 100 30
第一题用的python内置sort
line = input() nums = line.split(';')[0] nums = list(map(int,nums.split(','))) n = int(line.split(';')[1]) ji = [] ou = [] for num in nums: if num&1==1: ji.append(num) else: ou.append(num) ji.sort() ji.reverse() ou.sort() ou.reverse() if len(ou)>=n: ans = ou[:n] else: ans = ou + ji[:n-len(ou)] ans = list(map(str,ans)) print (','.join(ans))第二题回溯,深度优先搜索
s = int(input()) def cmp(s1,s2): if len(s1)!=len(s2): return False for i in range(len(s1)): if s1[i]!=s2[i]: return False return True for i in range(s): nums = [char for char in input()] news = [char for char in input()] n = len(nums) paths = [] def search(nums,luans,news,path,n): if n == 0: if cmp(luans,news): paths.append(path) return num = nums[0] nums = nums[1:] search(nums,luans,news,path+['d'],n-1) search(nums,[num]+luans,news,path+['l'],n-1) search(nums,luans+[num],news,path+['r'],n-1) search(nums,[],news,[],n) print ('{') for path in paths: print (' '.join(path)) print ('} ')第三题是dp的思路
n = int(input())#多少骰子 nums = list(map(int,input().split()))#每个骰子的可能结果数 ans = [[0 for i in range(51)] for j in range(50)]#初始化结果 maxnum = 0 for x in range(1,nums[0]+1):#初始化第1次的结果 ans[0][x] = 1 maxnum = max(maxnum,nums[0]) for i in range(1,n):#每个骰子 maxnum = max(maxnum,nums[i]) for j in range(1,maxnum+1):#可能的取值 if nums[i]>=j:#如果当前数值小于当前能取到的最大值 ans[i][j] = sum(ans[i-1][:j+1])+(j-1)*ans[i-1][j] else:#如果当前数值大于当前能取到的最大值 ans[i][j] = ans[i-1][j] * nums[i] all_ = 0 all_num = 0 for i in range(1,51): all_ += ans[n-1][i] all_num += ans[n-1][i]*i print ('%.2f'%(all_num/all_))
第四题leetcode类似题,但是二分查找没实现出来,暴力排序取第k个做的 30%
line = list(map(int,input().split())) n,m,k = line[0],line[1],line[2] ans = [[(i+1)*(j+1) for j in range(m)] for i in range(n)] nums = [] for a in ans: nums.extend(a) nums.sort() nums.reverse() print (nums[k])