Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 21f1f5f

Browse files
committed
solve problem Sort Characters By Frequency
1 parent 24b44c2 commit 21f1f5f

File tree

5 files changed

+244
-0
lines changed

5 files changed

+244
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,7 @@ All solutions will be accepted!
313313
|394|[Decode String](https://leetcode-cn.com/problems/decode-string/description/)|[java/py/js](./algorithms/DecodeString)|Medium|
314314
|938|[Range Sum Of Bst](https://leetcode-cn.com/problems/range-sum-of-bst/description/)|[java/py/js](./algorithms/RangeSumOfBst)|Medium|
315315
|71|[Simplify Path](https://leetcode-cn.com/problems/simplify-path/description/)|[java/py/js](./algorithms/SimplifyPath)|Medium|
316+
|451|[Sort Characters By Frequency](https://leetcode-cn.com/problems/sort-characters-by-frequency/description/)|[java/py/js](./SortCharactersByFrequency)|Medium|
316317

317318
# Database
318319
|#|Title|Solution|Difficulty|
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Sort Characters By Frequency
2+
We can solve this problem by heap
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
class Solution {
2+
class MaxHeap {
3+
class Node {
4+
Object item;
5+
int priority;
6+
7+
Node(Object item, int priority) {
8+
this.item = item;
9+
this.priority = priority;
10+
}
11+
}
12+
13+
ArrayList<Node> heap;
14+
MaxHeap() {
15+
this.heap = new ArrayList<Node>();;
16+
}
17+
18+
void push(Object item, int priority) {
19+
heap.add(new Node(item, priority));
20+
int pos = heap.size() - 1;
21+
int pPos = (pos % 2 == 0 ? pos - 2 : pos - 1) / 2;
22+
23+
while (pPos >= 0 && priority > heap.get(pPos).priority) {
24+
Node temp = heap.get(pPos);
25+
heap.set(pPos, heap.get(pos));
26+
heap.set(pos, temp);
27+
pos = pPos;
28+
pPos = (pos % 2 == 0 ? pos - 2 : pos - 1) / 2;
29+
}
30+
}
31+
32+
int size() {
33+
return heap.size();
34+
}
35+
36+
Object pop() {
37+
int size = heap.size();
38+
if (size == 0)
39+
throw new ArrayIndexOutOfBoundsException("pop from empty list");
40+
else if (size == 1)
41+
return heap.remove(0).item;
42+
43+
Object item = heap.get(0).item;
44+
int pos = 0;
45+
int maxChildPos = pos * 2 + 2;
46+
heap.set(0, heap.remove(size - 1));
47+
48+
if (maxChildPos < size - 1)
49+
maxChildPos = heap.get(maxChildPos).priority > heap.get(maxChildPos - 1).priority ? maxChildPos : maxChildPos - 1;
50+
else
51+
maxChildPos = maxChildPos - 1 < size - 1 ? maxChildPos - 1 : pos;
52+
53+
while (maxChildPos < size - 1 && heap.get(pos).priority < heap.get(maxChildPos).priority) {
54+
Node temp = heap.get(maxChildPos);
55+
heap.set(maxChildPos, heap.get(pos));
56+
heap.set(pos, temp);
57+
pos = maxChildPos;
58+
maxChildPos = pos * 2 + 2;
59+
60+
if (maxChildPos < size - 1)
61+
maxChildPos = heap.get(maxChildPos).priority > heap.get(maxChildPos - 1).priority ? maxChildPos : maxChildPos - 1;
62+
else
63+
maxChildPos = maxChildPos - 1 < size - 1 ? maxChildPos - 1 : pos;
64+
}
65+
66+
return item;
67+
}
68+
}
69+
70+
public String frequencySort(String s) {
71+
Map<Character, Integer> charMap = new HashMap<Character, Integer>();
72+
for (char c : s.toCharArray()) {
73+
if (charMap.get(c) == null)
74+
charMap.put(c, 1);
75+
else
76+
charMap.put(c, charMap.get(c) + 1);
77+
}
78+
79+
MaxHeap maxHeap = new MaxHeap();
80+
for (char c : charMap.keySet())
81+
maxHeap.push(c, charMap.get(c));
82+
83+
StringBuilder sb = new StringBuilder();
84+
while (maxHeap.size() > 0) {
85+
char c = (char) maxHeap.pop();
86+
for (int i = 0; i < charMap.get(c); i++)
87+
sb.append(String.valueOf(c));
88+
}
89+
return sb.toString();
90+
}
91+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
* @param {string} s
3+
* @return {string}
4+
*/
5+
var frequencySort = function(s) {
6+
let charMap = {}
7+
s.split('').forEach(c => {
8+
if (charMap[c] == undefined)
9+
charMap[c] = 1
10+
else
11+
charMap[c]++
12+
})
13+
14+
let maxHeap = new MaxHeap()
15+
Object.keys(charMap).forEach(key => {
16+
maxHeap.push(key, charMap[key])
17+
})
18+
19+
let res = ''
20+
while (maxHeap.size() > 0) {
21+
let key = maxHeap.pop()
22+
for (let i = 0; i < charMap[key]; i++)
23+
res += key
24+
}
25+
return res
26+
};
27+
28+
function MaxHeap() {
29+
this.heap = []
30+
};
31+
32+
MaxHeap.prototype.push = function(item, priority) {
33+
this.heap.push({item, priority})
34+
let pos = this.heap.length - 1,
35+
pPos = (pos % 2 == 0 ? pos - 2 : pos - 1) / 2
36+
37+
while (pPos >= 0 && priority > this.heap[pPos].priority) {
38+
let temp = this.heap[pos]
39+
this.heap[pos] = this.heap[pPos]
40+
this.heap[pPos] = temp
41+
pos = pPos
42+
pPos = (pos % 2 == 0 ? pos - 2 : pos - 1) / 2
43+
}
44+
};
45+
46+
MaxHeap.prototype.size = function() {
47+
return this.heap.length
48+
};
49+
50+
MaxHeap.prototype.pop = function() {
51+
let size = this.size()
52+
if (size == 0)
53+
throw new Error('pop form empty list')
54+
else if (size == 1)
55+
return this.heap.pop().item
56+
57+
let item = this.heap[0].item,
58+
pos = 0,
59+
maxChildPos = pos * 2 + 2
60+
this.heap[0] = this.heap.pop()
61+
62+
if (maxChildPos < size - 1)
63+
maxChildPos = this.heap[maxChildPos].priority > this.heap[maxChildPos - 1].priority ? maxChildPos : maxChildPos - 1
64+
else
65+
maxChildPos = maxChildPos - 1 < size - 1 ? maxChildPos - 1 : pos
66+
67+
while (maxChildPos < size - 1 && this.heap[pos].priority < this.heap[maxChildPos].priority) {
68+
let temp = this.heap[maxChildPos]
69+
this.heap[maxChildPos] = this.heap[pos]
70+
this.heap[pos] = temp
71+
pos = maxChildPos
72+
maxChildPos = pos * 2 + 2
73+
74+
if (maxChildPos < size - 1)
75+
maxChildPos = this.heap[maxChildPos].priority > this.heap[maxChildPos - 1].priority ? maxChildPos : maxChildPos - 1
76+
else
77+
maxChildPos = maxChildPos - 1 < size - 1 ? maxChildPos - 1 : pos
78+
}
79+
80+
return item
81+
};
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
class Solution(object):
2+
class MaxHeap(object):
3+
'''
4+
simple max heap for this solution
5+
'''
6+
def __init__(self):
7+
self.heap = []
8+
9+
def push(self, item, priority):
10+
self.heap.append({ 'item': item, 'priority': priority })
11+
pos = self.size() - 1
12+
p_pos = (pos - 2 if pos % 2 == 0 else pos - 1) / 2
13+
14+
while p_pos >= 0 and priority > self.heap[p_pos]['priority']:
15+
self.heap[pos], self.heap[p_pos] = self.heap[p_pos], self.heap[pos]
16+
pos = p_pos
17+
p_pos = (pos - 2 if pos % 2 == 0 else pos - 1) / 2
18+
19+
def size(self):
20+
return len(self.heap)
21+
22+
def pop(self):
23+
size = self.size()
24+
if size == 0:
25+
raise IndexError('pop form empty list')
26+
elif size == 1:
27+
return self.heap.pop()['item']
28+
29+
item = self.heap[0]['item']
30+
self.heap[0] = self.heap.pop()
31+
pos = 0
32+
max_child_pos = pos * 2 + 2
33+
if max_child_pos < size - 1:
34+
max_child_pos = max_child_pos if self.heap[max_child_pos]['priority'] > self.heap[max_child_pos - 1]['priority'] else max_child_pos - 1
35+
else:
36+
max_child_pos = max_child_pos - 1 if max_child_pos - 1 < size - 1 else pos
37+
38+
while max_child_pos < size - 1 and self.heap[pos]['priority'] < self.heap[max_child_pos]['priority']:
39+
self.heap[pos], self.heap[max_child_pos] = self.heap[max_child_pos], self.heap[pos]
40+
pos = max_child_pos
41+
max_child_pos = pos * 2 + 2
42+
if max_child_pos < size - 1:
43+
max_child_pos = max_child_pos if self.heap[max_child_pos]['priority'] > self.heap[max_child_pos - 1]['priority'] else max_child_pos - 1
44+
else:
45+
max_child_pos = max_child_pos - 1 if max_child_pos - 1 < size - 1 else pos
46+
47+
return item
48+
49+
def frequencySort(self, s):
50+
"""
51+
:type s: str
52+
:rtype: str
53+
"""
54+
char_map = {}
55+
for c in s:
56+
if not char_map.get(c):
57+
char_map[c] = 1
58+
else:
59+
char_map[c] += 1
60+
61+
max_heap = Solution.MaxHeap()
62+
for key, value in char_map.items():
63+
max_heap.push(key, value)
64+
65+
res = ''
66+
while max_heap.size() > 0:
67+
c = max_heap.pop()
68+
res += char_map[c] * c
69+
return res

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /