Python双指针击败100%
2021年5月2日 15:06
解题思路
让$i,j$从给定的start位置分别往两边走,谁先走到值为target的位置停下,返回走过的长度。![]()
代码
###python3
class Solution:
def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
i = j = start
n = len(nums)
while i>=0 or j<n:
if i>=0 and nums[i]==target:
return start-i
if j<n and nums[j]==target:
return j-start
i -= 1
j += 1
return 0