首页 > 9.19网易笔试(红蓝格子第一题),第四题只能通过70%。
头像
牛客921550822号
发布于 2021-09-19 17:37
+ 关注

9.19网易笔试(红蓝格子第一题),第四题只能通过70%。

第一题:
思路:连续颜色算成一块,寻找红色的块数、蓝色的块数,结果就是红蓝中比较小的块数+1。
import sys
N = int(sys.stdin.readline().strip())
value = list(sys.stdin.readline().strip())
blueCount = 0
tag = 0
for i in range(N):
    if value[i] == 'B' and tag == 0:
        tag = 1
    if tag == 1 and value[i] == 'R':
        tag = 0
        blueCount += 1
redCount = 0
tag = 0
for i in range(N):
    if value[i] == 'R' and tag == 0:
        tag = 1
    if tag == 1 and value[i] == 'B':
        tag = 0
        redCount += 1

if value[-1] == 'R':
    redCount += 1
else:
    blueCount += 1

print(min(blueCount, redCount) + 1)
第二题:
不能整除返回-1,能整除就分解质因数,结果就是质因数的数目。
import sys

def factorize(n):
    res = []
    i = 2
    while(i**2 <= n):
        while n % i == 0:
            res.append(i)
            n = n // i
        i += 1
    if n != 1:
        res.append(n)
    return len(res)

line = sys.stdin.readline().strip()
values = list(map(int, line.split()))
a = values[0]
b = values[1]

if a >= b&nbs***bsp;b % a != 0:
    print(-1)
else:
    print(factorize(b // a))


第三题:时间复杂度很宽松,暴力匹配就可以。
import sys

p = sys.stdin.readline().strip()
p = list(p)

def calculateCost(pattern):
    p = ['A','c','M','e','r']
    summation = 0
    for i in range(5):
        cost = 10
        if abs(ord(p[i]) - ord(pattern[i])) == 32:
            cost -= 5
        elif ord(p[i]) == ord(pattern[i]):
            cost -= 10
        elif p[i].isupper() == pattern[i].isupper():
            cost -= 5
        
        summation += cost

    return summation

res = 50
for i in range(0,len(p) - 4):
    pattern = p[i:i+5]
    summation = calculateCost(pattern)
    res = min(res, summation)
       
print(res)

第四题:我的思路是求等比数列的通项公式,最后结果是n(q-1)+1 = qk
q从2到n遍历求k即可,只能通过70%,求更好的思路。
import sys
import math
m = int(sys.stdin.readline().strip())

def calculate(x):
    for q in range(2, x):
        res = x*(q-1) + 1
        if abs(math.log(res)/math.log(q) - round(math.log(res)/math.log(q))) < 0.00001:
            print(str(round(math.log(res)/math.log(q))) + ' ' + str(q))
            return 

    
for i in range(m):
    value = int(sys.stdin.readline().strip())
    calculate(value)
    


全部评论

(1) 回帖
加载中...
话题 回帖