File tree Expand file tree Collapse file tree 1 file changed +67
-1
lines changed Expand file tree Collapse file tree 1 file changed +67
-1
lines changed Original file line number Diff line number Diff line change 1+ from collections import defaultdict
2+
13import solution
24from typing import *
5+ from sortedcontainers import SortedList
36
47
58class Solution (solution .Solution ):
69 def solve (self , test_input = None ):
710 return self .findXSum (* test_input )
811
912 def findXSum (self , nums : List [int ], k : int , x : int ) -> List [int ]:
10- pass
13+ cnt = defaultdict (int )
14+ L = SortedList () # 保存 tuple (出现次数,元素值)
15+ R = SortedList ()
16+ sum_l = 0 # L 的元素和
17+
18+ def add (val : int ) -> None :
19+ if cnt [val ] == 0 :
20+ return
21+ p = (cnt [val ], val )
22+ if L and p > L [0 ]: # p 比 L 中最小的还大
23+ nonlocal sum_l
24+ sum_l += p [0 ] * p [1 ]
25+ L .add (p )
26+ else :
27+ R .add (p )
28+
29+ def remove (val : int ) -> None :
30+ if cnt [val ] == 0 :
31+ return
32+ p = (cnt [val ], val )
33+ if p in L :
34+ nonlocal sum_l
35+ sum_l -= p [0 ] * p [1 ]
36+ L .remove (p )
37+ else :
38+ R .remove (p )
39+
40+ def l2r () -> None :
41+ nonlocal sum_l
42+ p = L [0 ]
43+ sum_l -= p [0 ] * p [1 ]
44+ L .remove (p )
45+ R .add (p )
46+
47+ def r2l () -> None :
48+ nonlocal sum_l
49+ p = R [- 1 ]
50+ sum_l += p [0 ] * p [1 ]
51+ R .remove (p )
52+ L .add (p )
53+
54+ ans = [0 ] * (len (nums ) - k + 1 )
55+ for r , in_ in enumerate (nums ):
56+ # 添加 in_
57+ remove (in_ )
58+ cnt [in_ ] += 1
59+ add (in_ )
60+
61+ l = r + 1 - k
62+ if l < 0 :
63+ continue
64+
65+ # 维护大小
66+ while R and len (L ) < x :
67+ r2l ()
68+ while len (L ) > x :
69+ l2r ()
70+ ans [l ] = sum_l
1171
72+ # 移除 out
73+ out = nums [l ]
74+ remove (out )
75+ cnt [out ] -= 1
76+ add (out )
77+ return ans
You can’t perform that action at this time.
0 commit comments