zoukankan      html  css  js  c++  java
  • 1184. Distance Between Bus Stops

    问题:

    给定n个汽车站之间的距离数组distances(相邻两个站相连,收尾站相连,可顺时针逆时针两个方向行驶)

    求start站和destination站之间的最短距离。

    Example 1:
    Input: distance = [1,2,3,4], start = 0, destination = 1
    Output: 1
    Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
    
    Example 2:
    Input: distance = [1,2,3,4], start = 0, destination = 2
    Output: 3
    Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
    
    Example 3:
    Input: distance = [1,2,3,4], start = 0, destination = 3
    Output: 4
    Explanation: Distance between 0 and 3 is 6 or 4, minimum is 4.
     
    Constraints:
    1 <= n <= 10^4
    distance.length == n
    0 <= start, destination < n
    0 <= distance[i] <= 10^4
    

            

    解法:

    从start站到destination站

    两个方向行驶的距离 之和=总distance之和。

    因此遍历所有distance

    left=min(start, destination)

    right=max(start, destination)

    当 i 在 [left, right)(左闭右开区间)时,为顺时针行驶距离,

    剩下距离求和,则为逆时针行驶距离。

    最后返回二者较小值。

    代码参考:

     1 class Solution {
     2 public:
     3     int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
     4         int res1=0;
     5         int res2=0;
     6         for(int i=0; i<distance.size(); i++){
     7             if(i>=min(start, destination) && i<max(start, destination)){
     8                 res1+=distance[i];
     9             }else{
    10                 res2+=distance[i];
    11             }
    12         }
    13         return min(res1, res2);
    14     }
    15 };
  • 相关阅读:
    ie 火狐兼容集锦
    ie css png
    jQuery插件——autoTextarea-文本框根据输入内容自适应高度
    比onload更快获取图片尺寸(转载)
    数据库性能问题排查
    项目管理_FindBugs的使用
    js动态获取子复选项并设计全选及提交
    SVN使用_获取某版本后改动的文件列表
    存储过程_把字符串转化为结果集
    Spring下如何配置bean
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13237755.html
Copyright © 2011-2022 走看看