需求:
环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。
环线上的公交车都可以按顺时针和逆时针的方向行驶。
返回乘客从出发点 start 到目的地 destination 之间的最短距离。
思路:要么顺着走,要么反着走,反着走的距离 = 距离总和 - 顺着走的距离
package JavaLeetCodeExercise20240916;
public class LeetCodeExercise {
public static void main(String[] args) {
int[] distance = {1,2,3,4};
Solution solution = new Solution();
System.out.println(solution.distanceBetweenBusStops(distance, 0, 3));
}
}
class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
int minDistance = 0;
int sumDistance = 0;
int ADistance = 0;
int length = distance.length;
boolean flag = true;
for (int i = 0; i < length; i++) {
sumDistance += distance[start];
if (start == destination) {
flag = false;
}
if (flag) {
ADistance += distance[start];
}
start = (start + 1) % length; // 循环队列经典写法
}
int anonterDistance = sumDistance - ADistance;
return ADistance < anonterDistance ? ADistance : anonterDistance;
}
}
标签:distance,Java,int,每日,距离,ADistance,start,length,LeetCode
From: https://blog.csdn.net/Aishangyuwen/article/details/142308498