zoukankan      html  css  js  c++  java
  • LeetCode 1029. Two City Scheduling (两地调度)

    题目标签:Greedy

      重新排序array, 根据到AB城市的距离进行排序:

        如果到B的距离远远大于A,那么把这个很小的A 排序到前面。

        排序完毕之后,排在越前面的都是相较于B,A更小的;排在越后面的都是相较于B,A更大的。

        那么可以在前一半 取A的值,后一半 取B的值。

        具体看code。

    Java Solution: 

    Runtime:  1 ms, faster than 96.15% 

    Memory Usage: 37.7 MB, less than 75.00%

    完成日期:02/19/2020

    关键点:根据情况 重新排序

    class Solution {
        public int twoCitySchedCost(int[][] costs) {
            /*
                这里是根据到AB城市的距离来进行排序,如果到B的距离远远大于A,那么得到的差值越小
                排序就越在前面,越应该选择到A点而不是去B
            */
            Arrays.sort(costs, (a, b) -> {
                return (a[0] - a[1]) - (b[0] - b[1]);
            });
            
            int minCost = 0;
            
            // take the smaller dist from A in first half of array, then take the smaller dist from B in second half;
            for(int i = 0; i < costs.length; i++) {
                if(i < costs.length / 2) {
                    minCost += costs[i][0];
                } else {
                    minCost += costs[i][1];
                }
            }
            
            return minCost;
        }
    }

    参考资料:LeetCode Discuss

    LeetCode 题目列表 - LeetCode Questions List

    题目来源:https://leetcode.com/

  • 相关阅读:
    ffmpeg
    HDU 1031 Design T-Shirt
    HDU 1029 Ignatius and the Princess IV
    HDU 1022 Train Problem I
    HDU 1017 A Mathematical Curiosity
    HDU 1015 Safecracker
    HDU 1002 A + B Problem II
    HDU 1070 Milk
    高精度算法(一)
    codeblocks 使用心得
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/12334520.html
Copyright © 2011-2022 走看看