Given an integer array nums and an integer k, return the
k most frequent elements. You may return the answer in any order.
nums=[1,1,1,2,2,3], k=2[1, 2]nums=[1,2,2,3,3,3], k=2[2, 3]nums=[4,4,4,6,6,1,1,1,1], k=2[1, 4]O(n)minH.offer(elem, freq)minH.size() > k: minH.poll() — evict least-frequent
We want the k largest frequencies. By keeping a min-heap
capped at size k, the root is always the weakest current candidate
(lowest frequency among our best k so far). When a new element arrives and makes the heap k+1, we
evict the root — guaranteed to be the least-valuable. After all unique keys are processed,
the heap holds exactly the answer. Runs in O(n log k) vs. O(n log n) for full sort.