繁体   English   中英

Python:需要帮助使用两个指针方法解决此问题

[英]Python: Need help solving this problem using two pointers method

我目前正在练习编码问题,发现这个问题称为“成功的咒语和药水对”,问题描述如下;

给你两个正数 integer arrays 法术和药水,长度分别为 n 和 m,其中 spells[i] 代表第 i 个法术的强度,potions[j] 代表第 j 个药水的强度。

您还将获得 integer 成功。 如果他们的力量的产品至少是成功的,那么咒语和药水对被认为是成功的。

返回一个长度为 n 的 integer 数组对,其中pairs[i] 是与第 i 个法术成功配对的药水数量。

Example 1:

Input: spells = [5,1,3], potions = [1,2,3,4,5], success = 7
Output: [4,0,3]
Explanation:
- 0th spell: 5 * [1,2,3,4,5] = [5,10,15,20,25]. 4 pairs are successful.
- 1st spell: 1 * [1,2,3,4,5] = [1,2,3,4,5]. 0 pairs are successful.
- 2nd spell: 3 * [1,2,3,4,5] = [3,6,9,12,15]. 3 pairs are successful.
Thus, [4,0,3] is returned.

Example 2:

Input: spells = [3,1,2], potions = [8,5,8], success = 16
Output: [2,0,2]
Explanation:
- 0th spell: 3 * [8,5,8] = [24,15,24]. 2 pairs are successful.
- 1st spell: 1 * [8,5,8] = [8,5,8]. 0 pairs are successful. 
- 2nd spell: 2 * [8,5,8] = [16,10,16]. 2 pairs are successful. 
Thus, [2,0,2] is returned.

我知道这个问题可以使用二分搜索来解决,但我的尝试是一种迭代尝试,它计算每个数组中每个成功元素的总数并将它们插入另一个数组。 但由于某种原因,我返回的数组全为零([0,0,0])。 这是我的尝试。 我将不胜感激在我的解决方案中找到错误的任何帮助,只是想学习,谢谢。

 def successfulPairs(self, spells, potions, success): arr = [] total = 0 first = 0 second = 0 while first < len(spells): res = spells[first] * potions[second] for i in range(len(potions)): if res >= success: total += 1 second += 1 first += 1 arr.append(total) total = 0 return arr

for循环每次通过循环时都会测试相同的res值。 增加second不会改变res的值。

您不需要使用指针(索引),只需遍历列表元素即可。 您可以使用sum() function 来计算总数,并使用生成器表达式遍历药水列表并进行乘法运算。

def successfulPairs(self, spells, potions, success):
    arr = []
    for spell in spells:
        total = sum(spell * potion >= success for potion in potions)
        arr.append(total)
    return arr

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM