Skip to content
Advertisement

Python priority queue- subsequent pops return wrong values after first pop?

I am trying to solve Leetcode #347 Top K Frequent elements using a priority queue. However, my code is failing some test cases.

Here is the code:

JavaScript

Here is stdout when running this with k = 2 and nums = [4,1,-1,2,-1,2,3]

JavaScript

Why does my code seem to skip over 2 as the the entry to return on the second call to q.get()?

It correctly returns -1 on the first time, but the second pop it returns 1 and not 2. I cannot find the reasoning for this. Please help!

Advertisement

Answer

the PriorityQue object does not sort items as your code implies you think. What you want to do instead is: 1- change q.put(num, -1*counts[num]) to q.put((-1 * counts[num], num)) 2- change cur = q.get() to cur = q.get()[1]

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement