其他分享
首页 > 其他分享> > 【Leetcode】1184. Distance Between Bus Stops

【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)。

标签:Distance,distance,int,Bus,1184,destination,start,s2,s1
来源: https://blog.csdn.net/qq_46105170/article/details/117731661