【每日一题】 1184. 公交站间的距离
避免每日太过咸鱼,一天搞定一道LeetCode算法题
一、题目描述
环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。
环线上的公交车都可以按顺时针和逆时针的方向行驶。
返回乘客从出发点 start 到目的地 destination 之间的最短距离。
提示:
- 1 <= n <= 10^4
- distance.length == n
- 0 <= start, destination < n
- 0 <= distance[i] <= 10^4
示例 1:
输入:distance = [1,2,3,4], start = 0, destination = 1
输出:1
解释:公交站 0 和 1 之间的距离是 1 或 9,最小值是 1。
示例 2:
输入:distance = [1,2,3,4], start = 0, destination = 2
输出:3
解释:公交站 0 和 2 之间的距离是 3 或 7,最小值是 3。
示例 3:
扫描二维码关注公众号,回复:
12438615 查看本文章

输入:distance = [1,2,3,4], start = 0, destination = 3
输出:4
解释:公交站 0 和 3 之间的距离是 6 或 4,最小值是 4。
二、题解
1. 解法一
解题思路:
这道题我是当作一道数学题来看待,相当于是一个环形跑道,在上面有多个站点,问题就是得到其中两个站点的最近距离,最简单的方式就是两个站点按照环形顺时针方向 得到 start 到 destination 之间的距离和 destination 到start 之间的距离,进行比较 得到最小值。
public static int distanceBetweenBusStops1(int[] distance, int start, int destination) {
if (start > destination) {
int temp = destination;
destination = start;
start = temp;
}
int distance1 = 0;
int distance2 = 0;
// 先获取0到start之间的距离
for (int i = 1; i <= start; i++) {
distance1 += distance[i - 1];
}
// 计算start到destination的距离
for (int i = start; i < destination; i++) {
distance2 += distance[i];
}
// 最后计算destination到0的距离
for (int i = destination; i < distance.length; i++) {
distance1 += distance[i];
}
return distance1 < distance2 ? distance1 : distance2;
}
2. 解法二
解题思路:
这种方式是在题解中观摩的,他的理解中直接无视起点终点的区别,纯粹看成环路计算,循环直接从0开始,起点终点均视为特殊的点,循环的时候计算特殊点间的正反两段距离,取偏小值输出就行。
public static int distanceBetweenBusStops2(int[] distance, int start, int destination) {
int n = distance.length;
// 通过mark来区分两点间的正反路径
int mark = 0;
int[] sum = new int[2];
for (int i = 0; i < n; i++) {
if (i == start || i == destination) {
mark = mark == 0 ? 1 : 0;
}
sum[mark] += distance[i];
}
return Math.min(sum[0], sum[1]);
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/distance-between-bus-stops
--------------最后感谢大家的阅读,愿大家技术越来越流弊!--------------
--------------也希望大家给我点支持,谢谢各位大佬了!!!--------------