题解 | #漂流船问题#

漂流船问题

https://www.nowcoder.com/practice/0e6cb06ec63148ed952f887a787f0103

import sys


# 公司组织团建活动,到某漂流圣地漂流,现有如下情况:
# 员工各自体重不一,第 i 个人的体重为 people[i],每艘漂流船可以承载的最大重量为 limit。
# 每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。
# 为节省开支,麻烦帮忙计算出载到每一个人所需的最小船只数(保证每个人都能被船载)。


def boatCount(lst, limit):
    # 开始计算
    lst.sort()

    if len(lst) == 1:
        if lst[0] <= limit:
            raise Exception("Max weight ecceded!")
        else:
            print(0)
            raise Exception("Max weight ecceded!")

    boat_count = 0
    l_index, r_index = 0, len(lst) - 1

    while l_index <= r_index:
        if l_index == r_index:
            if lst[l_index] <= limit:
                boat_count += 1
                break
            else:
                raise Exception("Max weight ecceded!")

        if lst[l_index] + lst[r_index] <= limit:
            l_index += 1
            r_index -= 1
            boat_count += 1
            continue
        else:
            if lst[r_index] > limit:
                raise Exception("Max weight ecceded!")
            boat_count += 1
            r_index -= 1

    return boat_count


people = []

if __name__ == "__main__":
    people = input().split()
    for i, j in enumerate(people):
        try:
            people[i] = int(j)
        except:
            raise Exception("Wrong input")
    boatWeightlimit = int(input())
    result = boatCount(people, boatWeightlimit)
    print(result)

全部评论

相关推荐

丿南烟丶:黑白模板吧,不要这样花哨的。 主要成就太空了,和获奖融在一起,写一两行就行了。 职业技能不要这样排,就传统的掌握精通什么什么然后举例补充的一些重要技术点。 自我介绍说实话也没啥用,可以删了。 把自己的两个项目方案细节补充上去,为什么这样设计,怎么设计,成果是什么按star法则来写 你要引导面试官来问你的技能和项目,你的获奖和自我介绍别人可能看都不看一眼或者不太在乎,重要的是展示你能干活的能力
点赞 评论 收藏
分享
09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务