451. Sort Characters By Frequency将单词中的字母按照从高频到低频的顺序输出

[抄题]:

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:
"tree" Output:
"eert" Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

[暴力解法]:

时间分析:

空间分析:

[优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

不知道怎么存进pq

[英文数据结构或算法,为什么不用别的数据结构或算法]:

只放一个hashmap元素:要用map.entrySet() 用得不多

Map.Entry代表一个哈希表实体

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

451. Sort Characters By Frequency将单词中的字母按照从高频到低频的顺序输出

[一刷]:

Map.Entry中的e.getKey()是不是字母,也不是对象。不用命名,直接存就行了

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

pq中存Map.Entry 代表一个哈希表实体

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

pq类中有类,类中有方法

PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(
new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b) {
return b.getValue() - a.getValue();
}
}
);

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

[是否头一次写此类driver funcion的代码] :

[潜台词] :

class Solution {
public String frequencySort(String s) {
//ini: res map
String res = new String();
Map<Character, Integer> map = new HashMap<>(); //cc
if (s == null || s.length() == 0) return res; //count char
char[] chars = s.toCharArray();
for (char c : chars) {
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
}
else map.put(c, 1);
} //pq
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue(
new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b) {
return b.getValue() - a.getValue();
}
}
); //append to answer
pq.addAll(map.entrySet());
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) {
Map.Entry e = pq.poll();
//char ch = e.getKey();
for (int i = 0; i < (int)e.getValue(); i++) {
sb.append(e.getKey());
}
} //return new string
return sb.toString();
}
}
上一篇:支持xcode6的缓动函数Easing以及使用示例


下一篇:JavaScript一个猜数字游戏