A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start and destination stops.
Example 1:
Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Explanation: Distance between 0 and 1 is 1 or 9, minimum is 1.
Example 2:
Example 2Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Explanation: Distance between 0 and 2 is 3 or 7, minimum is 3.
Example 3:
Example 3Constraints:
- 1 <= n <= 10^4
- distance.length == n
- 0 <= start, destination < n
- 0 <= distance[i] <= 10^4
Solution:
class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
if destination < start:
start, destination = destination, start
clockwise = sum(distance[start : destination])
cnt_clockwise = sum(distance) - clockwise
return min(clockwise, cnt_clockwise)
Explanation:
For this question, we just need to find the sum of distances of stops between start and destination, both clockwisely or counterclockwisely. Then we pick the minimum of these to as our answer. Just keep in mind that start could be greater than destination, so the clockwise and counterclockwise distance will be swapped in this case. Since we just need to find the minimum and don't care about directions(i.e. we don't care whether the minimal is from clockwise or counterclockwise), we can swap the start and destination at the beginning to make sure start is always less than destination, thus making our life easier.
本题我们只需要找到顺时针或逆时针之间起点和终点之间的停靠点距离之和即可。然后,我们选择其中的最小值作为答案。需要注意的是 start 可能大于destination,因此在这种情况下,顺时针和逆时针距离将完全相反。由于我们只需要找到两者最小值,而不关心具体方向(我们不关心这个最小值是来自顺时针或者逆时针),因此我们完全可以在一开始时交换起点和终点,使解题更轻松。
网友评论