题目347
https://leetcode.com/problems/top-k-frequent-elements/
347简单些,692是其变式,多了一种排序
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
代码
class Solution { class Data{ int num; int ncnt; Data(int num,int ncnt){ this.ncnt=ncnt; this.num=num; } } public int[] topKFrequent(int[] nums, int k) { int[] ans=new int[k]; Map<Integer,Integer> dataset=new HashMap<>(); for(int n:nums){ dataset.put(n,dataset.getOrDefault(n,0)+1);//统计频次 } PriorityQueue<Data> p=new PriorityQueue<Data>(new Comparator<Data>(){ @Override public int compare(Data d1,Data d2){ return d2.ncnt-d1.ncnt;//降序排列 } }); for(int n:dataset.keySet()){ p.offer(new Data(n,dataset.get(n)));//插入,进行排序 } for(int i=0;i<k;i++){ ans[i]=p.poll().num;//取出排序好的数 } return ans; } }
题目692
https://leetcode.com/problems/top-k-frequent-words/
数组中有一堆词,求数组中出现频次最高的前K的词
如果出现频次相同,则按字典序abc输出
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.
Example 2:
Input: words = ["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.
思路
优先队列,重点是怎么重写comparator,重写格式
//d1-d2升序排列(abcde,1234)
//d2-d1降序排列(edcba,4321)
PriorityQueue<数据结构> q=new PriorityQueue<>(new Comparator<数据结构>() {
@Override
public int compare(数据结构 d1, 数据结构d2) {
return d1-d2;
}
});
代码
重新建了个data类,更加直观,也有直接用hashmap的方法
class Solution { class Data{ String name; int cnt; Data(String name,int cnt){ this.name=name; this.cnt=cnt; } } public List<String> topKFrequent(String[] words, int k) { List<String> ans = new ArrayList<>(); Map<String,Integer> dataset=new HashMap<>(); for(String word:words){ dataset.put(word,dataset.getOrDefault(word,0)+1);//计算所有word的出现频次 } //d1-d2升序排列(abcde,1234) //d2-d1降序排列(edcba,4321) PriorityQueue<Data> q=new PriorityQueue<>(new Comparator<Data>() { @Override public int compare(Data d1, Data d2) { if(d1.cnt!=d2.cnt) return d2.cnt-d1.cnt;//频次不等,比较频次 return d1.name.compareTo(d2.name);//频次相等,比较字母排序 } }); for(String s:dataset.keySet()){ q.add(new Data(s,dataset.get(s))); } for(int i=0;i<k;i++){ ans.add(q.poll().name);//输出前k个频次高的 } return ans; } }