【力扣题解】1029. 两地调度
😊博主目前也在学习,有错误欢迎指正😊
🌈保持热爱 奔赴星海🌈
文章目录
一、题目
1、题目描述
公司计划面试 2n 人。给你一个数组 costs ,其中 costs[i] = [aCosti, bCosti] 。第 i 人飞往 a 市的费用为 aCosti ,飞往 b 市的费用为 bCosti 。
返回将每个人都飞到 a 、b 中某座城市的最低费用,要求每个城市都有 n 人抵达。
2、基础框架
- Java版本框架代码如下:
class Solution { public int twoCitySchedCost(int[][] costs) { }}
3、原题链接
1029. 两地调度
二、解题报告
1、思路分析
(1)假设让所有人都去b城市,并且在途中可以更改目的地。若一个人在去b城市的过程中更改了目的地,那么他的花费会增加costs[i][0] - costs[i][0],这个数可正可负,当costs[i][0] - costs[i][0]越小,相对于其他人来说,去a城市更划算,所以我们派costs[i][0] - costs[i]最小的n个人去a地即可。
2、代码详解
class Solution { public int twoCitySchedCost(int[][] costs) { int res = 0; Arrays.sort(costs, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return (o1[0] - o1[1]) - (o2[0] - o2[1]); } }); for (int i = 0; i < costs.length/2; i++) { res += costs[i][0]; } for (int i = costs.length/2; i < costs.length; i++) { res += costs[i][1]; } return res; }}
三、本题知识
自定义排序+贪心