刷题的日常-公交站间的距离

186 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情

刷题的日常

一天一题,保持脑子清爽

公交站间的距离

来自leetcode的1184题,题意如下:

环形公交路线上有n个站,按次序从0到n - 1进行编号。我们已知每一对相邻公交站之间的距离,distance[i]表示编号为i的车站和编号为(i + 1) % n的车站之间的距离。

  • 环线上的公交车都可以按顺时针和逆时针的方向行驶。
  • 返回乘客从出发点start到目的地destination之间的最短距离。

题目给出的用例如下: image.png

输入:distance = [1,2,3,4], start = 0, destination = 1
输出:1
解释:公交站 0 和 1 之间的距离是 1 或 9,最小值是 1。

image.png

输入:distance = [1,2,3,4], start = 0, destination = 2
输出:3
解释:公交站 0 和 2 之间的距离是 3 或 7,最小值是 3。

理解题意

由题意我们可以将条件整理如下:

  • 题目给定一个数组,代表公交车在当前站到下一个站的距离
  • 题目还给定了两个索引,一个是公交车开始地点,一个是结束地点
  • 数组是个环形数组
  • 要求返回最短的距离

做题思路

这道题也是比较简单,可以进行两趟扫描,汇总正向行驶和方向形式的距离,最后比较下两边的据里哪个比较短,返回最短那个就是了。 我采用的是第二种方法:

  • 直接从开始索引开始扫描
  • 扫描过程中汇总距离
  • 如果没到结束节点,继续扫描,汇总正向距离
  • 然后从结束节点开始扫描,汇总所有距离
  • 最后返回最长长度 和 开始节点到结束节点的距离取最小值

代码实现

public class Solution {
    public int distanceBetweenBusStops(int[] distance, int start, int destination) {
        int sum = 0, result;
        int len = distance.length;
        int idx = start;
        while (idx != destination) {
            sum += distance[idx];
            idx = ++idx % len;
        }
        result = sum;
        while (start != destination) {
            sum += distance[destination];
            destination = ++destination % len;
        }
        return Math.min(result, sum - result);
    }
}