给定一个由N 个字符串的数组arr[]和一个整数K ,任务是打印在arr[] 中出现次数最多的K 个字符串。如果两个或多个字符串具有相同的频率,则打印字典序最小的字符串。
注意: K的值总是小于或等于数组中不同元素的数量。
例子:
Input: str[] = {“geeks”, “geeksforgeeks”, “geeks”, “article”}, K = 1
Output: “geeks”
Explanation:
“geeks” –> 2
“geeksforgeeks” –> 1
“article” –> 1
Hence, the most occurring string is “geeks”
Input: str[] = {“car”, “bus”, “car”, “bike”, “car”, “bus”, “bike”, “cycle”}, K = 2
Output : “car”, “bus”
Explanation:
“car” –> 3
“bus” –> 2
“bike” –> 2
“cycle” –> 1
string “car” has highest frequency, string “bus” and “bike” both have second highest frequency, but string “bus” is lexicographically small because it has shorter length.
方法:
- 计算数组中每个字符串的频率并将其存储在 HashMap 中,其中字符串为键,频率为值。
- 现在,按照频率升序对这些键进行排序,这样做是为了将频率最低的键保持在顶部。
- 具有相同频率的字符串按字母顺序排列优先级,即字母顺序较大的字符串具有更高的优先级。
- 从 HashMap 中删除前N – K 个键值对。通过这样做,容器以相反的顺序留下具有最高频率的K 个键。
- 打印存储在 HashMap 中的字符串。
下面是上述方法的实现:
Java
// Java program for the above approach
import java.util.*;
class FrequentWords {
// Function that returns list of K
// most frequent strings
public static ArrayList
frequentWords(ArrayList arr, int K)
{
// Hash map to store the frequency
// of each string
HashMap Freq
= new HashMap<>();
// Set the default frequency of
// each string 0
for (String word : arr) {
Freq.put(word,
Freq.getOrDefault(word, 0)
+ 1);
}
// Using a priority queue to store
// the strings in accordance of the
// frequency and alphabetical order
// (if frequency is equal)
// Lambda expression is used set the
// priority, if frequencies are not
// equal than the string with greater
// frequency is returned else the
// string which is lexically smaller
// is returned
PriorityQueue Order
= new PriorityQueue<>(
(a, b)
-> (Freq.get(a) != Freq.get(b))
? Freq.get(a) - Freq.get(b)
: b.compareTo(a));
// Traverse the HashMap
for (String word : Freq.keySet()) {
Order.offer(word);
// Remove top (N - K) elements
if (Order.size() > K) {
Order.poll();
}
}
// Order queue has K most frequent
// strings in a reverse order
ArrayList ans
= new ArrayList<>();
while (!Order.isEmpty()) {
ans.add(Order.poll());
}
// Reverse the ArrayList so as
// to get in the desired order
Collections.reverse(ans);
return ans;
}
// Driver Code
public static void
main(String[] args)
{
int N = 3, K = 2;
// Given array
ArrayList arr
= new ArrayList();
arr.add("car");
arr.add("bus");
arr.add("car");
// Function Call
ArrayList ans
= frequentWords(arr, K);
// Print the K most occurring strings
for (String word : ans) {
System.out.println(word + " ");
}
}
}
car
bus
时间复杂度: O(N*log 2 N)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live