参考https://leetcode.com/problems/sort-characters-by-frequency/
class Solution {
public String frequencySort(String s) {
Map<Character,Integer> ch_freq = new HashMap<>();
TreeSet<Entry<Character,Integer>> es = new TreeSet<>((e1,e2)->{
int diff = e2.getValue()-e1.getValue();
return diff!=0 ? diff : e2.getKey()-e1.getKey();
});
for(char ch : s.toCharArray()) {
ch_freq.put(ch, ch_freq.getOrDefault(ch, 0)+1);
}
es.addAll(ch_freq.entrySet());
StringBuilder sb = new StringBuilder();
for(Entry<Character,Integer> e : es) {
char ch = e.getKey();
int freq = e.getValue();
while(--freq>=0) {
sb.append(ch);
}
}
return sb.toString();
}
}
TreeMap的排序是针对Key的,如果想对Map的Entry依照Value进行排序呢?
-
可利用TreeSet<Entry>。但是要注意,因为TreeSet的结点之间是严格的大小关系,所以为了防止覆盖:
int diff = e2.getValue()-e1.getValue();
return diff!=0 ? diff : e2.getKey()-e1.getKey(); -
利用ArrayList<Entry>+排序。时间复杂度是一样的,也不需要考虑上述的覆盖问题:https://leetcode.com/submissions/detail/480204194/
题外话,对于本题:map不如数组,数组天然支持排序。可考虑全部Value的取值范围,若较小,则完全可将value置为数组下标,如此时间可为O(n).具体可见于我的第二次正确提交