Leetcode 1184. Distance Between Bus Stops
You have a circular route of bus stops represented as an array where distance[i]
is the distance between the i-th
bus stop and the (i+1)th
bus stop (with the route wrapping around such that distance[n-1]
is the distance between the n-1
th bus stop and the 0th
bus stop). Given a start and destination stop, you are to find the shortest distance between the two stops.
Implement the function:
int distanceBetweenBusStops(vector<int>& distance, int start, int destination);
Q: Is start
always less than destination
, or can they be in any order?
A: They can be in any order. So you need to consider the direction in which you calculate the distance.
Q: Can start
and destination
be the same?
A: No, according to the problem, start and destination will always be different.
#include <vector>
#include <algorithm>
using namespace std;
int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
// If start is greater than destination, swap them to simplify the problem
if (start > destination) {
swap(start, destination);
}
int clockwiseDistance = 0;
for (int i = start; i < destination; ++i) {
clockwiseDistance += distance[i];
}
int totalDistance = 0;
for (int i = 0; i < distance.size(); ++i) {
totalDistance += distance[i];
}
int counterclockwiseDistance = totalDistance - clockwiseDistance;
return min(clockwiseDistance, counterclockwiseDistance);
}
n
is the length of the distance
array. This is because we need to traverse the array once to compute the total sum and another traversal 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?