Little modification to your code and this saves memory space for buckets. We don't need nums.length+1 number of buckets, we can limit number of buckets num.length/k+1.
PS: This code passed all the test cases.
Top K Frequent Elements
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.