公交最短距离-算法

题目

给定一个一维数组,其中每一个元素表示相邻公交站之间的距离,比如有四个公交站A,B,C,D,对应的距离数组为,1,2,3,4,如下图示

给定目标站X和Y,求他们之间最短的距离

解题

 遍历一次整个数组,将不再此区间内的和在此区间内的分别算一个综合,取其最小值

public class DistanceBetweenBusStopTest {

  public static void main(String[] args) {
    int[] distance = {1, 2, 3, 14};
    System.out.println(distanceBetweenBusStops(distance, 1, 4));
  }

  private static int distanceBetweenBusStops(int[] distance, int start, int destination) {
    int starti = Math.min(start, destination);
    int destinationi = Math.max(start, destination);

    int inLength = 0;
    int outLength = 0;
    for (int i = 0; i < distance.length; i++) {
      if (i + 1 >= starti && i + 1 < destinationi) {
        inLength += distance[i];
      } else {
        outLength += distance[i];
      }
    }
    return Math.min(inLength, outLength);
  }
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-04 12:30:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-04 12:30:06       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-04 12:30:06       82 阅读
  4. Python语言-面向对象

    2024-02-04 12:30:06       91 阅读

热门阅读

  1. 查找单词-算法(深度优先)

    2024-02-04 12:30:06       49 阅读
  2. 前端学习02

    2024-02-04 12:30:06       46 阅读
  3. C/C++ - 类模板

    2024-02-04 12:30:06       49 阅读
  4. Elasticsearch重建索引-修改索引字段类型

    2024-02-04 12:30:06       63 阅读
  5. windows安装git与git配置

    2024-02-04 12:30:06       56 阅读
  6. protobuf 序列化协议之数据结构

    2024-02-04 12:30:06       47 阅读
  7. SpringBoot打包

    2024-02-04 12:30:06       40 阅读
  8. 旋复代赭石汤原方

    2024-02-04 12:30:06       57 阅读
  9. 计算机科学导论(2)计算机如何存储音频

    2024-02-04 12:30:06       127 阅读
  10. gogs 搭建私人git服务器遇到的问题汇总

    2024-02-04 12:30:06       52 阅读
  11. MongoDB实战 – 创建和删除数据库

    2024-02-04 12:30:06       54 阅读