[LeetCode] 1029. 两地调度 ☆(贪心)

官方题解

作差排序

描述

公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]。

返回将每个人都飞到某座城市的最低费用,要求每个城市都有 N 人抵达。

示例:

输入:[[10,20],[30,200],[400,50],[30,20]]
输出:110
解释:
第一个人去 A 市,费用为 10。
第二个人去 A 市,费用为 30。
第三个人去 B 市,费用为 50。
第四个人去 B 市,费用为 20。

最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。
 

提示:

1 <= costs.length <= 100
costs.length 为偶数
1 <= costs[i][0], costs[i][1] <= 1000

解析

公司首先将这 2N 个人全都安排飞往 B市,再选出 N个人改变它们的行程,让他们飞往 A 市。如果选择改变一个人的行程,那么公司将会额外付出 price_A - price_B 的费用,这个费用可正可负。

因此最优的方案是,选出 price_A - price_B 最小的 N 个人,让他们飞往 A 市,其余人飞往 B 市。

算法

  • 按照 price_A - price_B 从小到大排序;

  • 将前 NN 个人飞往 A 市,其余人飞往 B 市,并计算出总费用。

代码

整体排序

class Solution {
    public int twoCitySchedCost(int[][] costs) {
        Arrays.sort(costs, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o1[1] - (o2[0] - o2[1]);
            }
        });
        int total = 0;
        int n = costs.length / 2;
        for (int i = 0; i < n; ++i) {
            total += costs[i][0] + costs[i + n][1];
        }
        return total;
    }
}

差值排序(更快点)

public class Solution {
    public int solve(int[][] costs) {
        int result = 0;
        int[] vals = new int[costs.length];
        for (int i = 0;i < costs.length;i++) {
            vals[i] = costs[i][0] - costs[i][1];     //算出飞两地的费用差值
            result = result + costs[i][1];           //将飞B地的费用加上差值作为暂时的结果
        }
        Arrays.sort(vals);                           //排序的目的是为了将最小的差值放在前面
        for (int i = 0;i < costs.length / 2;i++) {
            result += vals[i];                       //再用之前暂存的结果加上一半较小的差值便得到了到A地的费用,即前N个去B的费用通过差值换成去A的费用
        }
        return result;
    }
}
原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/11233670.html