字节跳动笔试08.28
第一题:20分,判断特征,哪些可以被计算,过了90%
n = int(input()) needs = [int(i) for i in input().split()] relations = [] for i in range(n-1): relations.append([int(i) for i in input().split()]) dic = {} for relation in relations: dic[relation[0]] = relation[1:] ans = [] for j in needs: flag = False if j not in dic: ans.append(1) else: seta = dic[j] for item in seta: if item in dic: flag = True setb = dic[item] if j in setb: ans.append(0) else: ans.append(1) if not flag: ans.append(1) print(" ".join(str(i) for i in ans))第二题:25分,输出最大子数组乘积位置,过了50%
n = int(input()) lens = [] subsets = [] for i in range(n): len_num = int(input()) lens.append(len_num) subsets.append([int(i) for i in input().split()]) def minmul(lis): n = len(lis) dp = [1]*n l,r = 0,0 res,ans = [],[] for i in range(n): if lis[i]==0: dp[i] = 0 else: if i>=1 and lis[i-1]==0: dp[i]= lis[i] else: dp[i]= dp[i-1]*lis[i] res = max(dp) for i,item in enumerate(dp): if item==0: l = i+1 if res==item: r = i ans.append([l+1,r+1]) return min(ans) for subset in subsets: print(" ".join(str(i) for i in minmul(subset)))
第三题,25分,翻转一次,输出最大子数组和 尝试暴力,过了20%
n = int(input()) nums = ([int(i) for i in input().split()]) l,r = 0,0 ans = 0 def maxsum(nums): # 子数组最大和 n = len(nums) dp = [0]*n for i in range(n): dp[i] = nums[i] for i in range(1,n): dp[i] += max(dp[i-1],0) return max(dp) for i in range(n): if nums[i]<0: l=i # 第二种是和后面的交换 for j in range(i+1,n): if nums[j]>0: r = j if l!=r: nums[l:r+1] = nums[l:r+1][::-1] ans = max(ans,maxsum(nums)) # 只能翻转一次,要翻转回去 nums[l:r+1] = nums[l:r+1][::-1] # 第一种是和前面的交换 for j in range(0,i): if nums[j]>0: r = j if l!=r: nums[l:r+1] = nums[l:r+1][::-1] ans = max(ans,maxsum(nums)) nums[l:r+1] = nums[l:r+1][::-1] print(ans)
第四题,30分,删去一个元素,输出K个元素子数组的最大和,暴力过了10%