Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
Input: words = ["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.
i’m trying to solve this problem using Frequencies and store the most ones and loop k times to get all of them but i have a problem i can’t return them as a lexicographical order
upd : i solved it thanks !
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
int n =words.size();
map<string ,int > Freq;
for (int i = 0 ; i< n;i++)
Freq[words[i]]++;
vector<pair<string ,int >>result;
vector<string>ans;
for (auto it : Freq)
result.push_back({it.first,it.second});
sort(result.begin(),result.end());
for (int i = 0 ; i < min(k,n);i++)
ans.push_back(result[i].first);
return ans;
}
};
>Solution :
you have to use compare function as a third parameter in the sort function.
compare function will sort the values as you want exactly!
class Solution {
public:
static bool cmp(pair<string ,int > &p1 , pair<string ,int > &p2)
{
if (p1.second == p2.second)return p1.first < p2.first ;
return p1.second > p2.second;
}
vector<string> topKFrequent(vector<string>& words, int k) {
int n =words.size();
map<string ,int > Freq;
for (int i = 0 ; i< n;i++)
Freq[words[i]]++;
vector<pair<string ,int >>result;
vector<string>ans;
for (auto &it : Freq)
result.push_back({it.first,it.second});
sort(result.begin(),result.end(),cmp);
for (int i = 0 ; i < min(k,n);i++)
ans.push_back(result[i].first);
return ans;
}
};