zoukankan      html  css  js  c++  java
  • LeetCode1029 两地调度(贪心+java自定义排序回顾)

    题目:

    公司计划面试 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

    思路:

    贪心。首先让所有的人都去城市B,这时的所有人总的花费为sumB。因为是AB两个城市都要有人,所以要将一半的人调到城市A去,那这一半的人调动之后,

    总的花费用(sumB+被调动人员AB两个城市之间花费的差价)。现在来分析一下,这被调动的一半人是怎么确定的:

    sumB是固定不变的了,那就通过这个差价来做文章了,因为这个差价是costA-costB得来的,所以要使总的花费最小,就要让差价最小的那一半人调到城市A

    去。

    import java.util.*;
    import java.math.*;
    
    class Solution {
        public int twoCitySchedCost(int[][] costs) {
            int sum = 0,n = costs.length/2;
            Arrays.sort(costs, new Comparator<int[]>() {
                @Override
                public int compare(int[] o1, int[] o2) {
                    return (o1[0]-o1[1])-(o2[0]-o2[1]);
                }
            });
            //System.out.println("length: "+costs.length);
            for(int i=0; i<costs.length; i++){
                //System.out.println(costs[i][0]+","+costs[i][1]);
                sum += costs[i][1];
            }
            for(int i=0; i<n; i++){
                sum += costs[i][0]-costs[i][1];
            }
            return sum;
        }
    }
    
    public class Main {
        public static void main(String[] args){
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            int[][] array = new int[4][2];
            for(int i=0; i<n; i++){
                array[i][0] = scanner.nextInt();
                array[i][1] = scanner.nextInt();
            }
            Solution solution = new Solution();
            System.out.println(solution.twoCitySchedCost(array));
        }
    }

    参考博友博客:

    https://blog.csdn.net/qq_41550842/article/details/96606437

    回顾了java中自定义排序的方法。

  • 相关阅读:
    The connection to adb is down, and a severe error has occured
    《Head First 设计模式》学习笔记——适配器模式 + 外观模式
    CF1062F Upgrading Cities
    2018-8-10-win10-uwp-App-to-app-communication-应用通信
    2018-8-10-win10-uwp-App-to-app-communication-应用通信
    2019-8-31-dotnet-动态代理魔法书
    2019-8-31-dotnet-动态代理魔法书
    2019-8-31-PowerShell-使用-WMI-获取信息
    2019-8-31-PowerShell-使用-WMI-获取信息
    2018-11-2-win10-uwp-通过-win2d-画出笔迹
  • 原文地址:https://www.cnblogs.com/sykline/p/12210667.html
Copyright © 2011-2022 走看看