【精】LintCode领扣算法问题答案:1895. 安排面试城市

    科技2022-08-05  112

    1895. 安排面试城市

    描述

    今天有 N 个面试者需要面试,公司安排了两个面试的城市A和B,每一个面试者都有到A城市的开销costA和到B城市的开销costB。公司需要将面试者均分成两拨,使得total cost最小。

    N是偶数2 <= N <= 1e5答案确保在int范围内1 <= costA,costB <= 1e6

    题目要求去A的人数和去B的人数相等。

    样例 1:

    输入: cost = [[5,4],[3,6],[1,8],[3,9]] 输出: 14 说明: 第一个和第二个人去B城市,剩下的去A城市

    原题传送门


    文章目录

    1895. 安排面试城市描述样例 1: 题解最后说两句声明


    题解

    public class Solution { /** * @param cost: The cost of each interviewer * @return: The total cost of all the interviewers. */ public int TotalCost(List<List<Integer>> cost) { // write your code here // 贪心算法,局部最优解,即是全局最优解 Collections.sort(cost, new Comparator<List<Integer>>() { @Override public int compare(List<Integer> o1, List<Integer> o2) { return (o1.get(0) - o1.get(1)) - (o2.get(0) - o2.get(1)); } }); int ret = 0; for (int i = 0; i < cost.size() / 2; ++i) { ret += cost.get(i).get(0); } for (int i = cost.size() / 2; i < cost.size(); ++i) { ret += cost.get(i).get(1); } return ret; } }

    最后说两句

    非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~

    作者水平有限,如果文章内容有不准确的地方,请指正。

    希望小伙伴们都能每天进步一点点。

    声明

    本文由二当家的白帽子博客原创,转载请注明来源,谢谢~

    Processed: 0.016, SQL: 8