字节跳动8.11后端开发笔试第二题
有原题,不过是求密码,不是求原码。用的是python,思路和大家也是一样的,一共写了三个版本,卡的要求都很细节,不过都是值得注意的地方
#第一版,过66.7 while True: try: N,K = map(int,input().split()) arr = input() arr = list(map(int,' '.join(arr).split())) orr = [arr[0]] i = 1 L = 1 while L<N: temp = 0 if i<=K-1: temp+=sum(orr[:i]) else: temp+=sum(orr[i-K+1:i]) temp+=arr[i] orr.append(temp%2) L+=1 i+=1 re = orr print(''.join(str(i) for i in re)) except: break第一版,提示超时,每次计算temp都是取得orr的K个元素求和,时间复杂度是K*N,所以进行优化,temp进行减头加尾,时间复杂度变为N,写了第二版
#第二版,过83 while True: try: N,K = map(int,input().split()) arr = input() arr = list(map(int,' '.join(arr).split())) orr = [arr[0]] i = 1 #print(orr) flag = 0 while len(orr)<N: #print(arr[i],orr) temp = 0 if i<=K-1: temp+=sum(orr[:i]) flag = temp else: temp = flag #temp+=sum(orr[i-K+1:i]) temp+=orr[i-1]-orr[i-K] flag = temp temp+=arr[i] orr.append(temp%2) #print('抑或之后',orr) i+=1 re = orr print(''.join(str(i) for i in re )) except:# Exception as a: #print(a) break第二版,提示超出内存,这是做题过程中第二次碰到,第一次是在shopee,那一次没找出问题所在,这一次,想到,输入字符串变成数组可能会导致内存超出,尝试改了一下,不改变字符串,继续提交第三版
#第三版 ac while True: try: N,K = map(int,input().split()) arr = input() #arr = list(map(int,' '.join(arr).split())) orr = arr[0] i = 1 flag = 0 while len(orr)<N: temp = flag if i<K: temp+=int(orr[i-1]) flag = temp else: temp+=int(orr[i-1])-int(orr[i-K]) flag = temp temp+=int(arr[i]) orr+=str(temp%2) #print(orr) i+=1 #re = orr #print(''.join(str(i) for i in re )) print(orr) except:# Exception as a: #print(a) break第三版终于ac了,小细节还挺多,平时计算求和直接取数组某一段,还有习惯于对数组进行操作,所以需要类型转换导致内存超出。习惯还需养好。