1184.公交站间的距离
链接:1184.公交站间的距离
难度:Easy
标签:数组
简介:返回乘客从出发点 start 到目的地 destination 之间的最短距离。
题解 1 - cpp
- 编辑时间:2022-03-29
- 内存消耗:8.6MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
int comp(vector<int>& distance, int start, int destination, int f) {
int sum = 0;
while (start != destination) {
if (f == 1) sum += distance[start];
start += f;
if (start == distance.size())
start = 0;
else if (start == -1)
start = distance.size() - 1;
if (f == -1) sum += distance[start];
}
return sum;
}
int distanceBetweenBusStops(vector<int>& distance, int start,
int destination) {
return min(comp(distance, start, destination, 1),
comp(distance, start, destination, -1));
}
};
题解 2 - rust
- 编辑时间:2022-07-24
- 内存消耗:2.1MB
- 编程语言:rust
- 解法介绍:遍历。
impl Solution {
pub fn distance_between_bus_stops(distance: Vec<i32>, start: i32, destination: i32) -> i32 {
let n = distance.len() as i32;
let (mut sum1, mut sum2) = (0, 0);
let (mut cur1, mut cur2) = (start, destination);
let mut i = start;
while i != destination {
sum1 += distance[i as usize];
i = (i + 1) % n;
}
i = destination;
while i != start {
sum2 += distance[i as usize];
i = (i + 1) % n;
}
sum1.min(sum2)
}
}
题解 3 - python
- 编辑时间:2024-09-16
- 执行用时:44ms
- 内存消耗:17.34MB
- 编程语言:python
- 解法介绍:向左遍历和向右遍历。
class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
n = len(distance)
def run(offset: int) -> int:
cur = start
val = 0
while cur != destination:
if offset == 1: val += distance[cur]
cur = (cur + offset) % n
if offset == -1: val += distance[cur]
return val
return min(run(v) for v in [1, -1])