Leetcode 1184. Distance Between Bus Stops
You are given an integer array distance
where distance[i]
describes the distance between the i-th
bus stop and the (i+1)-th
bus stop. You are also given two integers start
and destination
that indicate the start and destination stops, respectively (the bus stops are in a circular route).
Return the shortest distance between these two stops.
start
be greater than destination
?
start
can be either greater than or less than destination
.distance
will always be non-empty and contain positive integers.start
and destination
will always be valid indices of the array.start
be equal to destination
?
start
equals destination
, the shortest distance is zero.start
to destination
in a clockwise direction and sum the distances.destination
to start
in a clockwise direction and sum the distances.public class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
if (start == destination) {
return 0;
}
int totalDistance = 0;
for (int dist : distance) {
totalDistance += dist;
}
int clockwiseDistance = 0;
int counterClockwiseDistance = 0;
int i = start;
while (i != destination) {
clockwiseDistance += distance[i];
i = (i + 1) % distance.length;
}
counterClockwiseDistance = totalDistance - clockwiseDistance;
return Math.min(clockwiseDistance, counterClockwiseDistance);
}
}
N
is the number of bus stops (length of the distance
array):
start
to destination
to compute the clockwise distance.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?