使用Python编写查找目标元素的最小距离程序
假设我们有一个数组nums和两个不同的值target(target必须存在于nums中)和start,我们必须找到一个索引i,使得nums [i] = target,且|i-start|最小。我们必须返回|i-start|。
因此,如果输入是nums = [3,4,5,6,7],target = 7和start = 2,则输出将是2,因为只有一个与目标匹配的值,即nums[4],因此i = 4。现在|4-2| = 2。
为了解决这个问题,我们将遵循以下步骤:
- minimum := infinity
-
for i in range 0 to size of nums, do
- if nums[i] is same as target, then
- if |i – start| < minimum, then
-
minimum := |i – start|
- if nums[i] is same as target, then
-
return minimum
让我们看下面的实现以获得更好的理解−
更多Python相关文章,请阅读:Python 教程
示例
from math import inf
def solve(nums, target, start):
minimum = inf
for i in range(len(nums)):
if nums[i] == target:
if abs(i - start) < minimum:
minimum = abs(i - start)
return minimum
nums = [3,4,5,6,7]
target = 7
start = 2
print(solve(nums, target, start))
输入
[3,4,5,6,7], 7, 2
输出
2