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.
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"]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.PriorityQueue;import java.util.Queue;public class TopKFrequentWords {public static void main(String[] args) {String[] strs = { "i", "love", "link", "i", "love", "coding" };int k = 2;List<String> freq = topKFrequent(strs, k);System.out.println(Arrays.asList(freq));}// function to find the top k// frquent stringsstatic List<String> topKFrequent(String[] words, int k) {Map<String, Integer> hashmap = new HashMap<>();// count the frequency of wordsfor (String s : words)hashmap.put(s, hashmap.getOrDefault(s, 0) + 1);Queue<String> pq = new PriorityQueue<>((a, b) -> hashmap.get(a).equals(hashmap.get(b)) ?a.compareTo(b) : hashmap.get(b) - hashmap.get(a));// add element in priority queuefor (String s : hashmap.keySet())pq.add(s);List<String> ans = new ArrayList<>();for (int i = 0; i < k; i++)ans.add(pq.poll());return ans;}}
C++
#include <bits/stdc++.h>using namespace std;//comparator used for sortingstatic bool cmp(pair<int, pair<string, int>> a, pair<int,pair<string, int>> b){if (a.first == b.first){return a.second.first < b.second.first;}return a.first > b.first;}//function to find the top k//frquent stringsvector<string> topKFrequent(vector<string> &words, int k){map<string, int> mp;for (int i = 0; i < words.size(); i++)mp[words[i]]++;vector<pair<int, pair<string, int>>> v;for (int i = 0; i < words.size(); i++){v.push_back({mp[words[i]], {words[i], i}});}sort(v.begin(), v.end(), cmp);set<string> st;vector<string> res;for (int i = 0; i < v.size() && k > 0; i++){if (st.find(v[i].second.first) == st.end()){res.push_back(v[i].second.first);k--;}st.insert(v[i].second.first);}return res;}int main(){vector<string> strs = {"i", "love", "link", "i", "love", "coding"};int k = 2;vector<string> freq = topKFrequent(strs, k);cout << "[";for (int i = 0; i < freq.size() - 1; i++)cout << freq[i] << ", ";cout << freq[freq.size() - 1] << "]";return 0;}
No comments:
Post a Comment