Python教程

leetcode 1848. Minimum Distance to the Target Element (python)

本文主要是介绍leetcode 1848. Minimum Distance to the Target Element (python),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

描述

Given an integer array nums (0-indexed) and two integers target and start, find an index i such that nums[i] == target and abs(i - start) is minimized. Note that abs(x) is the absolute value of x.

Return abs(i - start).

It is guaranteed that target exists in nums.

Example 1:

Input: nums = [1,2,3,4,5], target = 5, start = 3
Output: 1
Explanation: nums[4] = 5 is the only value equal to target, so the answer is abs(4 - 3) = 1.

Example 2:

Input: nums = [1], target = 1, start = 0
Output: 0
Explanation: nums[0] = 1 is the only value equal to target, so the answer is abs(0 - 0) = 0.

Example 3:

Input: nums = [1,1,1,1,1,1,1,1,1,1], target = 1, start = 0
Output: 0
Explanation: Every value of nums is 1, but nums[0] minimizes abs(i - start), which is abs(0 - 0) = 0.

Note:

1 <= nums.length <= 1000
1 <= nums[i] <= 10^4
0 <= start < nums.length
target is in nums.

解析

根据题意,就是在 nums 中找出 target ,并且要使得 target 对应的索引和 start 的绝对值是最小的,说明 nums 中不止有一个 target ,只需要遍历 nums ,只要是 target ,就在列表中记录当前索引和 start 的绝对值,遍历结束在列表中去最小值即可。

解答

class Solution(object):
    def getMinDistance(self, nums, target, start):
        """
        :type nums: List[int]
        :type target: int
        :type start: int
        :rtype: int
        """
        result = []
        for i in range(len(nums)):
            if nums[i] == target:
                result.append(abs(i-start))
        return min(result)

运行结果

Runtime: 36 ms, faster than 90.69% of Python online submissions for Minimum Distance to the Target Element.
Memory Usage: 13.6 MB, less than 60.86% of Python online submissions for Minimum Distance to the Target Element.

原题链接:https://leetcode.com/problems/minimum-distance-to-the-target-element/

您的支持是我最大的动力

这篇关于leetcode 1848. Minimum Distance to the Target Element (python)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!