当S比较大的时候,可以采用树状数组。
class BIT: def __init__(self, n): self.n = n # n为原数组的长度 self.tree = [0] * (n + 1) @staticmethod def lowbit(x): return x & (-x) def query(self, idx): ret = 0 while idx > 0: ret += self.tree[idx] idx -= BIT.lowbit(idx) return ret def update(self, idx, v): # v是更新前后的插值 while idx <= self.n: self.tree[idx] += v idx += BIT.lowbit(idx) class Solution: def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int: ans = 0 l = len(arr) bit = BIT(1002) for j in range(l): for k in range(j+1,l): if abs(arr[j]-arr[k])<=b: lb = max(0,arr[j]-a,arr[k]-c) rb = min(1001,arr[j]+a,arr[k]+c) if rb>=lb: ans+=bit.query(rb+1)-bit.query(lb) if lb>0 else bit.query(rb+1) bit.update(arr[j]+1,1) return ans