1184-公交站间的距离

1184:公交站间的距离

题目介绍

vSPL7Q.png

解题思路

  • 这是一道简单的题
  • 由于公交车只能顺时针或逆时针移动,而且所有点的移动顺序是固定的,例如从1到3的顺序就只有1,2,3或是倒着走,因为其他方式的路程无疑会更长
  • 所以只需要计算全部路程的长度和其顺序走或逆序走的路程数,然后选择较小的数值就是最短距离

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int distanceBetweenBusStops(int[] distance, int start, int destination) {
int sum = 0;
int part1 = 0;
if(start > destination){
int tmp = start;
start = destination;
destination = tmp;
}
for(int i = 0; i < distance.length; i++){
sum += distance[i];
}
for(int i = start; i < destination; i++){
part1 += distance[i];
}
if(sum - part1 < part1){
return sum-part1;
}else{
return part1;
}
}
}

简单的一题!!!

[1.jpg

作者

Yzdong

发布于

2022-07-24

更新于

2023-04-14

许可协议

评论