Python程序检查一个列表的反转子列表是否可以形成第二个列表
假设我们有两个数字列表,称为 A 和 B。我们必须在 A 中取一些子列表并将其反转。然后检查是否可以将 A 转换为 B。我们可以取子列表并将其反转任意次数。
因此,如果输入类似于 A = [2, 3, 4, 9, 10],B = [4, 3, 2, 10, 9],则输出将为 True,因为我们可以反转 [2,3,4] 和 [9,10]。
要解决此问题,我们将遵循以下步骤:
- res := 一个映射,最初为空
- 对于 nums 中的每个 n,执行以下操作:
- res[n] := res[n] + 1
- 对于 target 中的每个 t,执行以下操作:
- res[t] := res[t] - 1
- 当 res 的值中的所有元素都与 0 相同的时候返回 true。
让我们看看以下实现以获得更好的理解:
示例
from collections import defaultdict class Solution: def solve(self, nums, target): res = defaultdict(int) for n in nums: res[n] += 1 for t in target: res[t] -= 1 return all(n == 0 for n in res.values()) ob = Solution() A = [2, 3, 4, 9, 10] B = [4, 3, 2, 10, 9] print(ob.solve(A, B))
输入
[2, 3, 4, 9, 10], [4, 3, 2, 10, 9]
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
True
广告