@@ -9,8 +9,7 @@ def topKFrequent(nums, k):
99 else :
1010 freqs [num ] = 1
1111
12- buckets = [None for i in xrange (max (freqs .keys ())+ 1 )]
13-
12+ buckets = [None for i in xrange (max (freqs .values ())+ 1 )]
1413 for num in freqs :
1514 freq = freqs [num ]
1615 if buckets [freq ]:
@@ -22,21 +21,26 @@ def topKFrequent(nums, k):
2221 i = len (buckets )- 1
2322 addedCount = 0
2423 offset = 0
25- while addedCount < k :
26- while not buckets [i - offset - addedCount ]:
24+ while addedCount < k and i - offset > 0 :
25+ while not buckets [i - offset ]:
2726 offset += 1
28- ret += buckets [i - offset - addedCount ]
29- addedCount += 1
27+ ret += buckets [i - offset ]
28+ addedCount += len (buckets [i - offset ])
29+ offset += 1
3030
3131 return ret
3232
3333def testTopKFrequent ():
3434 assert set (topKFrequent ([], 0 )) == set ([])
3535 assert set (topKFrequent ([1 ], 1 )) == set ([1 ])
36+ assert set (topKFrequent ([- 1 , - 1 ], 1 )) == set ([- 1 ])
3637 assert set (topKFrequent ([1 ,1 ,1 ,2 ,2 ,3 ], 2 )) == set ([1 , 2 ])
3738 assert set (topKFrequent ([- 1 ,- 1 ,- 1 ,2 ,2 ,3 ], 2 )) == set ([- 1 , 2 ])
3839 assert set (topKFrequent ([1 ,1 ,1 ,2 ,2 ,3 ], 3 )) == set ([1 , 2 , 3 ])
40+ assert set (topKFrequent ([1 ,1 ,1 ,2 ,2 ,2 ,3 ,3 ,3 ], 3 )) == set ([1 , 2 , 3 ])
3941 assert set (topKFrequent ([1 , 2 , 3 , 4 , 5 ], 1 )) == set ([1 , 2 , 3 , 4 , 5 ])
42+ assert set (topKFrequent ([4 ,1 ,- 1 ,2 ,- 1 ,2 ,3 ], 2 )) == set ([- 1 , 2 ])
43+ assert set (topKFrequent ([3 ,2 ,3 ,1 ,2 ,4 ,5 ,5 ,6 ,7 ,7 ,8 ,2 ,3 ,1 ,1 ,1 ,10 ,11 ,5 ,6 ,2 ,4 ,7 ,8 ,5 ,6 ], 10 )) == set ([1 ,2 ,5 ,3 ,7 ,6 ,4 ,8 ,10 ,11 ])
4044
4145def main ():
4246 testTopKFrequent ()
0 commit comments