华为笔试0920题解

100-100-97,最后一题太太太复杂了实在调不出最后的3%来了。

T1

n = int(input())
nums = list(map(int, input().split()))
target = int(input())
idx = [i for i, x in enumerate(nums) if x == target]
if not idx:
    print(-1, -1)
elif idx[-1] - idx[0] == len(idx) - 1:
    print(idx[0], idx[-1])
else:
    for i in range(1, len(idx)):
        if idx[i] - idx[i-1] != 1:
            print(idx[i], idx[i-1])
            break

T2

bfs模板题

from collections import deque
m, n = map(int, input().split())
mat = [list(map(int, input().split())) for _ in range(m)]
q = deque()
dist = [[-1] * n for _ in range(m)]
for i in range(m):
    if mat[i][0] == 1:
        q.append((i, 0))
        dist[i][0] = 0
while q:
    i, j = q.popleft()
    for di, dj in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
        ni, nj = i + di, j + dj
        if 0 <= ni < m and 0 <= nj < n and mat[ni][nj] == 1 and dist[ni][nj] == -1:
            dist[ni][nj] = dist[i][j] + 1
            q.append((ni, nj))
print(min([dist[i][-1] for i in range(m) if dist[i][-1] != -1], default=-1))

T3

import re, sys
def cal(a, b, op):
    if op == '+': return a + b
    elif op == '-': return a - b
    elif op == '*': return a * b
    elif op == '/': return a // b
    else: return b

variables = dict()

for line in sys.stdin.readlines():
    line = line.strip()
    if line.startswith("let "):
        var, value = line[4:].replace(" ", "").split("=")
        res = re.match(r"[a-zA-Z_][a-zA-Z0-9_]*$", var)
        if not res:
            print("<syntax-error>")
            continue
        value = value.replace("+", " + ").replace("-", " - ").replace("*", " * ").replace("/", " / ")
        lst = value.split()
        ans, op = 0, None
        for ele in lst:
            if ele in "+-*/":
                op = ele
            elif ele.isdigit():
                ans = cal(ans, int(ele), op)
            elif ele not in variables or variables[ele] == "<undefined>":
                ans = "<undefined>"
                break
            else:
                ans = cal(ans, variables[ele], op)
        variables[var] = ans
    
    elif line.startswith("out("):
        var = line[4:-1]
        if var not in variables or variables[var]=="<undefined>":
            print("<undefined>")
        elif variables[var] < -2147483648:
            print("<underflow>")
        elif variables[var] > 2147483647:
            print("<overflow>")
        else:
            print(variables[var])

全部评论
还得是python爷,C++写死了,都没骗到10%
5 回复 分享
发布于 2023-09-20 22:08 广东
C++看到最后一题了我直接交卷,亇的这种题真恶心人
点赞 回复 分享
发布于 2023-09-21 14:04 北京

相关推荐

西南山:哥,你的技能是在报菜单吗
点赞 评论 收藏
分享
qz鹿:*** 祝他毕业就失业
点赞 评论 收藏
分享
评论
26
63
分享
牛客网
牛客企业服务