leetcode 1848. Minimum Distance to the Target Element (python)
2021/6/5 14:22:30
本文主要是介绍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)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型