携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第1天,点击查看活动详情
测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。
怎么才能提高我们的编程能力呢,刷LeetCode是最佳的途径之一,话不多数,刷题走起~
一、题目描述:
-
题目内容
-
题目示例
-
题目解析
- 1 <= n <= 10^4
- distance.length == n
- 0 <= start, destination < n
- 0 <= distance[i] <= 10^4
二、思路分析:
我们拿到本题,读取题目要求在环形公路上求出指定的两个车站的最短距离。知道题目要求后,我们仍然要对题目进行审题,需要明确如下细节点:
- 环形公路上的n个车站,车站的编号是0~n-1
- 环形公路上的车可以顺时针和逆时针方向运行
- 环形公路上两点i~j车站顺时针距离是distance[i]+...+distance[j-1]
那么解答本题,我们可以使用模拟方法求出顺时针d1和逆时针d2两个距离后,返回最短的距离作为结果。 那怎么求两个车站距离,饶饶小脑瓜,怎么又是一道眼睛会的手不会的题目呀,冷静一下学习思路吧
- 首先要统一计算方式,因此我们让start和destination两个始终保持
start <= destination - 当 start > destination 时,start 与 destination 进行交换
- 两个车站的距离,可以使用列表索引截取来进行计算
- 顺时针距离d1:取头不取尾,即sum(distance[start:destination])
- 逆时针距离d2:需要分为两段,一个取destination开始到distance末尾的distance[destination:],一个取从0开始到start结束的distance[:start]
按照上述对示例 [5,4,3,2] start=1,destination=3,进行如下图形推理如下:
根据以上思路,我们不难使用Python快速实现,代码如下:
class Solution(object):
def distanceBetweenBusStops(self, distance, start, destination):
"""
:type distance: List[int]
:type start: int
:type destination: int
:rtype: int
"""
if start > destination:
start,destination = destination,start
d1 = sum(distance[start:destination])
d2 = sum(distance[destination:]) + sum(distance[:start])
return min(d1,d2)
解答本题,我们也可以不用列表截取方法来求距离,只需要做好判断即可,思路大致如下:
- 同上述方法一样,需要提前假设start<=destination
- 使用一个for循环,范围在len(distance)内
- 当 i >= start and i < destination 时,则是计算的是顺时针距离,d1 += distance[i]
- 反之,则是计算的是逆时针距离,d2 += distance[i]
- 对两个距离d1,d2进行比较,返回最小值
class Solution(object):
def distanceBetweenBusStops(self, distance, start, destination):
d1,d2 = 0,0
if start > destination:
start,destination = destination,start
for i in range(len(distance)):
if i >= start and i < destination:
d1 += distance[i]
else:
d2 += distance[i]
return min(d1,d2)
三、总结:
本题考察是对列表索引遍历思想,同时需要知道顺时针和逆时针在distance列表中起始点,AC提交记录如下:
- 时间复杂度:O(n),n为distance长度
- 空间复杂度:O(1),没有使用额外空间
以上是本期内容,欢迎大佬们点赞评论,下期见~~~