692.Top K Frequent Words

1-Sorting + HashTable

Learned Lambda Expression

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>();
        for(String s : words){
            map.put(s, map.getOrDefault(s, 0) + 1);
        }
        List<String> candidates = new ArrayList(map.keySet());
        Collections.sort(candidates, new Comparator<String>(){
            @Override
            public int compare(String s1, String s2){
                int cnt1 = map.get(s1);
                int cnt2 = map.get(s2);
                if(cnt1 != cnt2){
                    return cnt2 - cnt1;
                }
                else{
                    return s1.compareTo(s2);
                }
            }
        });

        List<String> ans = new ArrayList<>();
        for(int i = 0; i < k; i++){
            ans.add(candidates.get(i));
        }
        return ans;
    }
}

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> count = new HashMap();
        for (String word: words) {
            count.put(word, count.getOrDefault(word, 0) + 1);
        }
        List<String> candidates = new ArrayList(count.keySet());
        Collections.sort(candidates, (w1, w2) -> count.get(w1) != count.get(w2) ?
                count.get(w2) - count.get(w1) : w1.compareTo(w2));

        return candidates.subList(0, k);
        }
    }
class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>();
        for(String s : words){
            map.put(s, map.getOrDefault(s, 0) + 1);
        }
        List<String> candidates = new ArrayList(map.keySet());
        Collections.sort(candidates, (String c1, String c2)->{
            int cmp = map.get(c2) - map.get(c1);
            if(cmp == 0)
                cmp = c1.compareTo(c2);
            return cmp;
        });

        List<String> ans = new ArrayList<>();
        for(int i = 0; i < k; i++){
            ans.add(candidates.get(i));
        }
        return ans;
    }
}

2- Heap

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>();
        for(String s : words){
            map.put(s, map.getOrDefault(s, 0) + 1);
        }
        Queue<String> heap = new PriorityQueue<String>(k, (w1, w2) -> 
            map.get(w1) == map.get(w2) ? w1.compareTo(w2) : map.get(w2) - map.get(w1));

        for(String word : map.keySet()){
            heap.offer(word);

        }
        List<String> ans = new ArrayList<>();
        for(int i = 0; i < k; i++){
            ans.add(heap.poll());
        }
        return ans;
    }
}

results matching ""

    No results matching ""