【Leetcode】1184. Distance Between Bus Stops

题目地址:

https://leetcode.com/problems/distance-between-bus-stops/

有 n n n个车站,在一个环上,给定相邻站的距离,再给定两个不同的站点。车可以沿着顺时针或逆时针走(方向中途不能变),问从起点到终点的最短距离。

代码如下:

public class Solution {
    public int distanceBetweenBusStops(int[] distance, int start, int destination) {
        int s1 = 0, s2 = 0;
        for (int i = start; i != destination; i = (i + 1) % distance.length) {
            s1 += distance[i];
        }
    
        for (int i = destination; i != start ; i = (i + 1) % distance.length) {
            s2 += distance[i];
        }
        
        return Math.min(s1, s2);
    }
}

时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。

上一篇:非父子组件间传值——Bus/总线机制


下一篇:ScreenToGif录屏转gif图片