【力扣题解】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;
    }
}

三、本题知识

自定义排序+贪心

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值