用 Python 检查有多少查询找到有效的算术序列的程序
pythonserver side programmingprogramming更新于 2026/1/5 23:08:17
假设我们有一个名为 nums 的数字列表,还有查询列表。其中每个查询元素包含 [i, j]。因此,此查询询问来自 [i, j](包括两者)的 nums 子列表是否是算术序列。所以最后我们必须找到返回 true 的查询的数量。
因此,如果输入为 nums = [2, 4, 6, 8, 7, 6, 5, 2] queries = [[3, 4],[0, 3],[2, 4]],则输出将为 2,因为 [2, 4, 6, 8] 是算术序列,所以查询 [0, 3] 为真。而对于 [8, 7] 也是一个等差序列,所以查询 [3, 4] 也是正确的。但是 [6, 8, 7] 不是等差数列,所以 [2, 4] 不成立。
为了解决这个问题,我们将遵循以下步骤 −
- 如果 nums 为空,则
- 返回 0
- n := nums 的大小
- diff := 一个列表,其中包含元素 (nums[i + 1] - nums[i]),每个 i 在 0 到 n - 2 的范围内
- rle := 一个大小为 (n - 1) 的列表并用 0 填充
- 对于 i 在 0 到 n - 2 的范围内,do
- 如果 i > 0 且 diff[i] 与 diff[i - 1] 相同,则
- rle[i] := rle[i - 1] + 1
- 否则,
- rle[i] := 1
- 如果 i > 0 且 diff[i] 与 diff[i - 1] 相同,则
- ans := 0
- 对于查询中的每个 (i, j),执行
- 如果 i 与 j 相同,则
- ans := ans + 1
- 否则,
- 如果 rle[j - 1] >= (j - i),则 ans := ans + (1),否则0)
- 如果 i 与 j 相同,则
- 返回 ans
示例
让我们看看下面的实现以便更好地理解 −
def solve(nums, queries): if not nums: return 0 n = len(nums) diff = [nums[i + 1] - nums[i] for i in range(n - 1)] rle = [0] * (n - 1) for i in range(n - 1): if i > 0 and diff[i] == diff[i - 1]: rle[i] = rle[i - 1] + 1 else: rle[i] = 1 ans = 0 for i, j in queries: if i == j: ans += 1 else: ans += rle[j - 1] >= (j - i) return ans nums = [2, 4, 6, 8, 7, 6, 5, 2] queries = [[3, 4],[0, 3],[2, 4]] print(solve(nums, queries))
输入
[2, 4, 6, 8, 7, 6, 5, 2], [[3, 4],[0, 3],[2, 4]]
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

