347. Top K Frequent Elements
Problem
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Explanation
My approach: HashMap and stream sorting
I solve this by first counting how many times each number appears, then sorting by frequency to pick the top k. I use a HashMap called repeatedNums to track each number and its count. As I iterate through the array, if a number already exists in the map, I increment its count; otherwise, I add it with a count of 1. Once I have all the frequencies, I convert the map to a stream, sort it by value in descending order (most frequent first), and collect it back into a LinkedHashMap to preserve the sorted order. Finally, I iterate through the sorted map's keys, copying the first k elements into my result array. This approach is straightforward and readable, using Java streams to handle the sorting elegantly.
Time: O(n log n) due to sorting the map entries
Space: O(n) for the HashMap and sorted map