1029--两地调度(思维)

题目

公司计划面试 2n 人。给你一个数组 costs ,其中 costs[i] = [aCosti, bCosti] 。第 i 人飞往 a 市的费用为 aCosti ,飞往 b 市的费用为 bCosti 。

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

示例 1:

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

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

链接:https://leetcode-cn.com/problems/two-city-scheduling

解答

算法

点击查看代码
public class OneZeroTwoNine {
    public static 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 n=costs.length/2;
        int sum=0;
        for(int i=0;i<n;i++){
           sum+=costs[i][0]+costs[i+n][1];
        }
        return sum;
    }
}
posted @ 2022-04-09 17:11  是徐洋洋呀  阅读(70)  评论(0)    收藏  举报