难度:中等
公司计划面试 2n 人。给你一个数组 costs ,其中 costs[i] = [aCosti, bCosti] 。第 i 人飞往 a 市的费用为 aCosti ,飞往 b 市的费用为 bCosti 。
返回将每个人都飞到 a 、b 中某座城市的最低费用,要求每个城市都有 n 人抵达。
提示:
- 2 * n == costs.length
- 2 <= costs.length <= 100
- costs.length 为偶数
- 1 <= aCosti, bCosti <= 1000
示例 1:
输入:costs = [[10,20],[30,200],[400,50],[30,20]]
输出:110
解释:
第一个人去 a 市,费用为 10。
第二个人去 a 市,费用为 30。
第三个人去 b 市,费用为 50。
第四个人去 b 市,费用为 20。
最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。
示例 2:
输入:costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
输出:1859
示例 3:
输入:costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
输出:3086
这是一道贪心思维很经典的思考类型,每个人飞往A和飞往B的金额已经展示出来了,那我们做以下极端思考。 甲飞往A只需要1块钱,飞往B需要10000块钱,这个人应该飞往哪儿?肯定飞往A啊,为什么? 因为飞往A比飞往B便宜。 知道这句话,我们就可以解题了。我们将每位顾客按照飞往A的金额-飞往B的金额差值来进行排序。 排在前面的肯定应该飞往A,而排在后面的人就理所应当的要飞往B了。。。然后根据总人数折半数组,分别sum后求和即可
class Solution:
def twoCitySchedCost(self, costs):
costs.sort(key = lambda x: x[0] - x[1])
costa = sum(i for i,_ in costs[:len(costs)//2])
costb = sum(i for _,i in costs[len(costs)//2:])
return costa + costbclass Solution:
def twoCitySchedCost(self, costs):
return sum(cost[0] if index < len(costs)//2 else cost[1] for index,cost in enumerate(sorted(costs,key = lambda x: x[0] - x[1])))
欢迎关注我的公众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。
有喜欢力扣刷题的小伙伴可以加我微信(King_Uranus)互相鼓励,共同进步,一起玩转超级码力!
我的个人博客:https://qingfengpython.cn