Skip to content

Latest commit

 

History

History
138 lines (124 loc) · 4.86 KB

692. Top K Frequent Words.md

File metadata and controls

138 lines (124 loc) · 4.86 KB

Given a non-empty list of words, return the k most frequent elements.

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Input words contain only lowercase letters.

Solution

  • mine

    Runtime: 5 ms, faster than 99.58%, Memory Usage: 46.8 MB, less than 5.36% of Java online submissions

    public List<String> topKFrequent(String[] words, int k) {
        Map<String, Integer> map = new HashMap<>();
        for (String word : words) {
            //words's item all is not the same
            map.put(word, map.getOrDefault(word, -1) + 1);
        }
        PriorityQueue<String>[] queueArray = new PriorityQueue[words.length];
        for (String key : map.keySet()) {
            int count = map.get(key);
            if (queueArray[count] == null) {
                queueArray[count] = new PriorityQueue<String>();
            }
            queueArray[count].add(key);
        }
        List<String> res = new ArrayList<>();
        for (int i = queueArray.length - 1; i >= 0 && k > 0; i--) {
            if (queueArray[i] != null) {
                int size = queueArray[i].size();
                if (k >= size) {
                    while (queueArray[i].size() > 0) {
                        res.add(queueArray[i].poll());
                    }
                    k -= size;
                } else {
                    while (k > 0) {
                        res.add(queueArray[i].poll());
                        k--;
                    }
                    break;
                }
            }
        }
        return res;
    }
    
    • the leetcode solution

      • Sorting: Runtime: 7 ms, faster than 57.39%, Memory Usage: 46.2 MB, less than 5.36% of Java online submissions
      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).equals(count.get(w2)) ?
                  w1.compareTo(w2) : count.get(w2) - count.get(w1));
      
          return candidates.subList(0, k);
      }
      
      • Heap: Runtime: 8 ms, faster than 17.01%, Memory Usage: 46.6 MB, less than 5.36% of Java online submissions
      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);
          }
          PriorityQueue<String> heap = new PriorityQueue<String>(
                  (w1, w2) -> count.get(w1).equals(count.get(w2)) ?
                  w2.compareTo(w1) : count.get(w1) - count.get(w2) );
      
          for (String word: count.keySet()) {
              heap.offer(word);
              if (heap.size() > k) heap.poll();
          }
      
          List<String> ans = new ArrayList();
          while (!heap.isEmpty()) ans.add(heap.poll());
          Collections.reverse(ans);
          return ans;
      }
      
    • the most votes Runtime: 7 ms, faster than 57.39%, Memory Usage: 46 MB, less than 5.36% of Java online submissions

    public List<String> topKFrequent(String[] words, int k) {
    
        List<String> result = new LinkedList<>();
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < words.length; i++) {
            if (map.containsKey(words[i]))
                map.put(words[i], map.get(words[i]) + 1);
            else
                map.put(words[i], 1);
        }
    
        PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
                (a, b) -> a.getValue() == b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue() - b.getValue()
        );
    
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            pq.offer(entry);
            if (pq.size() > k)
                pq.poll();
        }
    
        while (!pq.isEmpty())
            result.add(0, pq.poll().getKey());
    
        return result;
    }