LintCode领扣 题解 |Microsoft 面试题:Gas Station ii

题目描述

一辆汽车在一条笔直的道路上行驶,一开始有original单位的汽油。这条笔直的道路上有n个加油站,第i个加油站距离汽车出发位置的距离为distance[i]单位距离,可以给汽车加apply[i]单位汽油。汽车每行驶1单位距离会消耗1单位的汽油,假设汽车的油箱可以装无限多的汽油。目的地距离汽车出发位置的距离为target,请问汽车能否到达目的地,如果可以返回最少的加油次数,否则返回-1

思路点拨

考虑贪心,每次都用能到达并且能加最多油的加油站加油。

考点分析

本题考察了用优先队列来贪心的思想。对于汽车能到达的加油站,显然采用能提供油最多的加油站加油,这样才能保证到达目的地后加油次数最少,这个贪心的思想很有特色很值得借鉴。

参考程序

http://www.jiuzhang.com/solution/gas-station-ii/

/**
* 本参考程序来自九章算法,由 @华助教 提供。版权所有,转发请注明出处。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,
* - Big Data 项目实战班,算法面试高频题班, 动态规划专题班
* - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code
*/ 

public class Solution {
    /**
     * @param target: The target distance
     * @param original: The original gas
     * @param distance: The distance array
     * @param apply: The apply array
     * @return: Return the minimum times
     */
    class Station {
        public int d;
        public int gas;
        public Station(int d, int gas) {
            this.d = d;
            this.gas = gas;
        }
    }

    public static Comparator<Station> gasComparator = new Comparator<Station>(){
        public int compare(Station a, Station b) {
            return b.gas - a.gas;
        }
    };
    public static Comparator<Station> dComparator = new Comparator<Station>(){
        public int compare(Station a, Station b) {
            return a.d - b.d;
        }
    };

    public int getTimes(int target, int original, int[] distance, int[] apply) {
        // Write your code here
        Queue<Station> q = new PriorityQueue<Station>(distance.length, gasComparator);
        Station[] s = new Station[distance.length];
        for(int i = 0; i < distance.length; i++) {
            s[i] = new Station(distance[i], apply[i]);
        }
        Arrays.sort(s, dComparator);
        int ans = 0;
        int i = 0;
        while(original < target && i < distance.length) {
            while(i < distance.length && original >= s[i].d) {
                q.offer(s[i]);
                i++;
            }
            Station now = q.poll();
            if(now == null) {
                break;
            }
            original += now.gas;
            ans++;
        }
        if(original >= target) {
            return ans;
        } else {
            return -1;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 专业考题类型管理运行工作负责人一般作业考题内容选项A选项B选项C选项D选项E选项F正确答案 变电单选GYSZ本规程...
    小白兔去钓鱼阅读 13,416评论 0 13
  • 本题考察的是最大子序列和 题目描述 在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。你...
    小怪兽大作战阅读 6,089评论 0 1
  • 形态与质感在小魔静的线条中得到了恰如其份的表达。这种艺术的精准难得可贵,喜欢小魔静的线条
    胡尼克阅读 1,634评论 2 2
  • 熊猫唐飞阅读 3,493评论 0 49
  • 小孩子:妈妈,人死了会去天堂吗? 妈妈:天堂是一种想像,谁也不知道天堂什么样子。 小孩子:那人死了是不是什么都没有...
    rainchxy阅读 1,477评论 0 1

友情链接更多精彩内容