zoukankan      html  css  js  c++  java
  • leet code 853,car fleet

    链接:https://www.lintcode.com/problem/car-fleet/description

    题意:有好多车和它们的位置,速度,如果后边车在终点前追上前边的,则可以形成一个车队,问最终到达终点的有几个车队;

    直接想比较难,算一下它们到终点的时间,如果后边车的时间小于等于前边车的时间则一定可以追上,否则它自己就形成一个车队;

    1,用个TreeMap建立位置和时间之间的映射,位置由大到小,所以TreeMap的first存-position;

    code:

     1 class Solution {
     2 public:
     3     /**
     4      * @param target: the target
     5      * @param position: the initial position
     6      * @param speed: the speed
     7      * @return: How many car fleets will arrive at the destination
     8      */
     9     int carFleet(int target, vector<int> &position, vector<int> &speed) {
    10         // Write your code here
    11         //sort 
    12         int res=0; double cur=0;
    13         map<int ,double> pos2time;
    14         for(int i=0; i<position.size(); ++i)
    15         {
    16             pos2time[-position[i]]=(double)(target-position[i])/speed[i];
    17         }
    18         for(auto a : pos2time)
    19         {
    20             if(a.second <= cur) continue;
    21             cur = a.second;
    22             ++res;
    23         }
    24         return res;
    25     }
    26 };

    2,用优先队列直接维护;

    code;

     1 class Solution {
     2 public:
     3     /**
     4      * @param target: the target
     5      * @param position: the initial position
     6      * @param speed: the speed
     7      * @return: How many car fleets will arrive at the destination
     8      */
     9     int carFleet(int target, vector<int> &position, vector<int> &speed) {
    10         // Write your code here
    11         //sort 
    12         int res=0; double cur=0;
    13         priority_queue<pair<int ,int> > q;
    14         for(int i=0; i<position.size(); i++)
    15         {
    16             q.push({position[i],speed[i]});
    17         }
    18         while(!q.empty()){
    19             auto t=q.top();
    20             q.pop();
    21             double pos2time=(double) (target-t.first)/t.second;
    22             if(pos2time<=cur) continue;
    23             cur= pos2time;
    24             ++res;
    25         }
    26         return res;
    27     }
    28 };
  • 相关阅读:
    hadoop3.2.0集群搭建的一些坑!
    springboot整合elasticJob实战(纯代码开发三种任务类型用法)以及分片系统,事件追踪详解
    Flask接口返回JSON格式数据自动解析
    Struts2--国际化
    Struts2--标签tag
    Struts2-OGNL
    Struts2--拦截器Interceptor
    Struts2--struts.xml详解
    Spring--事务管理
    Spring--JDBC
  • 原文地址:https://www.cnblogs.com/sweetlittlebaby/p/12691066.html
Copyright © 2011-2022 走看看