C/C++教程

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

这篇关于【Leetcode】1184. Distance Between Bus Stops的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!