python的超时

YoungDubby edited 8 月,2 周前

每次到第五个时就超时 了

from collections import defaultdict

# 解决函数,返回查询区间内恰好出现两次的数字数量
def solve(nums, queries):
    answers = []
    for l, r in queries:
        # 在每个查询中,用两个哈希表分别跟踪整体出现次数和当前区间的出现次数
        overall_count = defaultdict(int)
        interval_count = defaultdict(int)
        for i in range(l - 1, r):
            overall_count[nums[i]] += 1
            if overall_count[nums[i]] == 2:  # 如果数字整体上恰好出现两次
                interval_count[nums[i]] += 1
            elif overall_count[nums[i]] == 3:  # 如果数字整体上出现三次
                interval_count[nums[i]] -= 1
        
        # 计算区间内恰好出现两次的数字数量
        twice_count = sum(1 for count in interval_count.values() if count == 1)
        answers.append(twice_count)
    
    return answers

# 读取输入
n, q = map(int, input().split())
nums = list(map(int, input().split()))
queries = [list(map(int, input().split())) for _ in range(q)]

# 处理查询并输出结果
answers = solve(nums, queries)
for answer in answers:
    print(answer)

Comments