华为OD机试分享20220627

作者:忍无限
链接:https://www.nowcoder.com/discuss/974077?toCommentId=13387871
来源:牛客网

第一题 字符串分割-水仙花数

题目描述
给定非空字符串s,将该字符串分割成一些子串,使每个子串的ASCII码值的和均为水仙花数。
1、若分割不成功,则返回0
2、若分割成功且分割结果不唯一,则返回-1
3、若分割成功且分割结果唯一,则返回分割后子串的数目

输入描述

输入字符串的最大长度为200

答案参加这个大佬的。

第二题
小华是个很有对数字很敏感的小朋友,他觉得数字的不同排列方式有特殊美感。某天,小华突发奇想,如果数字多行排列,第一行1个数,第二行2个,第三行3个,即第n行有n个数字,并且奇数行正序排列,偶数行逆序排列,数字依次累加。这样排列的数字一定很有意思。聪明的你能编写代码帮助小华完成这个想法吗?
————————————————


import sys
arr = []
for line in sys.stdin.readlines():
    if line == '\n':
        break
    arr.append(list(map(int, line.split(' '))))
if len(arr) == 1:
    print(arr[0])
arr.sort(key=lambda x: x[0])
comm_section = []
for i in range(len(arr) - 1):
    for j in range(i + 1, len(arr)):
        if arr[i][-1] >= arr[j][0]:
            comm_section.append([arr[j][0], min(arr[i][-1], arr[j][-1])])
            if len(comm_section) == 1:
                print(comm_section)
comm_section.sort(key=lambda x: x[0])
l = len(comm_section)
i = 0
while i <= l-2:
    if comm_section[i][-1] > comm_section[i+1][0]:
        comm_section[i][-1] = max(comm_section[i][-1], comm_section[i+1][-1])
        comm_section.pop(i+1)
        l-=1
    else:
        i+=1
    print(comm_section)


答案参考这个大佬的,写了python版本。

第三题
区间重叠问题

给定一组闭区间,其中部分区间存在交集。任意两个给定区间的交集,称为公共区间(如:[1,2],[2,3]的公共区间为[2,2],[3,5],[3,6]的公共区间为[3,5])。公共区间之间若存在交集,则需要合并(如:[1,3],[3,5]区间存在交集[3,3],须合并为[1,5])。按升序排列输出合并后的区间列表。

输入描述:

一组区间列表,

区间数为N:

0 <= N <= 1000;

区间元素为X:

-10000 <= X <= 10000。

输出描述:

升序排列的合并后区间列表

示例1

输入

0 3

1 3

3 5

3 6

输出

1 5

说明

[0,3]和[1,3]的公共区间为[1,3],[0,3]和[3,5]的公共区间为[3,3],[0,3]和[3,6]的公共区间为[3,3],[1,3]和[3,5]的公共区间为[3,3],[1,3]和[3,6]的公共区间为[3,3],[3,5]和[3,6]的公共区间为[3,5],公共区间列表为[[1,3],[3,3],[3,5]];[1,3],[3,3],[3,5]存在交集,须合并为[1,5]。

import sys
arr = []
for line in sys.stdin.readlines():
    if line == '\n':
        break
    arr.append(list(map(int, line.split(' '))))
if len(arr) == 1:
    print(arr[0])
arr.sort(key=lambda x: x[0])
comm_section = []
for i in range(len(arr) - 1):
    for j in range(i + 1, len(arr)):
        if arr[i][-1] >= arr[j][0]:
            comm_section.append([arr[j][0], min(arr[i][-1], arr[j][-1])])
            if len(comm_section) == 1:
                print(comm_section)
comm_section.sort(key=lambda x: x[0])
l = len(comm_section)
i = 0
while i <= l-2:
    if comm_section[i][-1] > comm_section[i+1][0]:
        comm_section[i][-1] = max(comm_section[i][-1], comm_section[i+1][-1])
        comm_section.pop(i+1)
        l-=1
    else:
        i+=1
    print(comm_section)

答案参考某个大佬的,写了python版本。

注:答案后续整理,东拼西凑,代码能力有限,欢迎大家参考交流。

#华为OD机考#
全部评论
楼主yyds,借楼谢谢! 深圳急聘华为OD:10+2起步(211以上+2),一本以上私聊。拿到offer的同学帮点赞。 另资源互换捞人私聊。
1 回复
分享
发布于 2022-07-29 18:44
感谢楼主分享
点赞 回复
分享
发布于 2022-07-13 21:09
滴滴
校招火热招聘中
官网直投

相关推荐

点赞 评论 收藏
转发
6 33 评论
分享
牛客网
牛客企业服务