链接:https://leetcode.cn/problems/distance-between-bus-stops/solution/by-xun-ge-v-p073/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目
示例
思路
解题思路
模拟
直接按照题目给定要求进行模拟即可
遍历数组,枚举区间start - destination的元素并且累加保存为min,在枚举区间destination - start的元素并且累加保存为max,判断min和max的大小并输出
代码
int distanceBetweenBusStops(int* distance, int distanceSize, int start, int destination){
int max = 0;
int min = 0;
if(start > destination)//方便遍历枚举
{
int t = destination;
destination = start;
start = t;
}
for(int i = start; i < destination; i++)//遍历区间start - destination
{
min += distance[i];
}
for(int i = destination; i != start;)//遍历区间destination - start
{
max += distance[i];
i++;
i = i % distanceSize;
}
return max > min ? min : max;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/distance-between-bus-stops/solution/by-xun-ge-v-p073/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间空间复杂度