-
Notifications
You must be signed in to change notification settings - Fork 71
/
No179.largest-number.js
105 lines (91 loc) · 2.42 KB
/
No179.largest-number.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* Difficulty:
* Medium
*
* Desc:
* Given a list of non negative integers, arrange them such that they form the largest number.
*
* Example:
* given [3, 30, 34, 5, 9], the largest formed number is 9534330.
*
* Note:
* The result may be very large, so you need to return a string instead of an integer.
*
* 将数组中的数字组合成最大的数字。利用最大堆
*/
class Heap {
constructor(arr) {
this.heap = [...arr];
for (let i = this.heap.length - 1; i >= 0; i -= 1) {
this.sortWithChild(i + 1);
}
}
more(index1, index2) {
const num1 = this.heap[index1 - 1] + '';
const num2 = this.heap[index2 - 1] + '';
const n1 = Number(num1[0]);
const n2 = Number(num2[0]);
if (n1 > n2) {
return true;
} else {
return Number(num1 + num2) > Number(num2 + num1);
}
}
exchange(index1, index2) {
const tmp = this.heap[index1 - 1];
this.heap[index1 - 1] = this.heap[index2 - 1];
this.heap[index2 - 1] = tmp;
}
enqueue(child) {
this.heap.push(child);
const childIndex = this.heap.length;
this.sortWithFather(childIndex);
}
sortWithFather(childIndex) {
const fatherIndex = Math.floor(childIndex / 2);
if (fatherIndex <= 0) return;
if (this.more(childIndex, fatherIndex)) {
this.exchange(childIndex, fatherIndex);
this.sortWithFather(fatherIndex);
}
}
sortWithChild(fatherIndex) {
if (fatherIndex <= 0) return;
const childIndex1 = fatherIndex * 2;
if (childIndex1 > this.heap.length) return;
if (this.more(childIndex1, fatherIndex)) {
this.exchange(childIndex1, fatherIndex);
}
const childIndex2 = fatherIndex * 2 + 1;
if (childIndex2 > this.heap.length) return;
if (this.more(childIndex2, fatherIndex)) {
this.exchange(childIndex2, fatherIndex);
}
this.sortWithChild(childIndex1);
this.sortWithChild(childIndex2);
}
get head() {
this.exchange(1, this.heap.length);
const result = this.heap.pop();
this.sortWithChild(1);
return result;
}
get length() {
return this.heap.length;
}
}
/**
* @param {number[]} nums
* @return {string}
*/
var largestNumber = function(nums) {
const heap = new Heap(nums);
const result = [];
while (heap.length) {
const num = heap.head;
if (!result.length && num === 0) continue;
result.push(num);
}
return result.length ? result.join('') : '0';
};
largestNumber([3, 30, 34, 5, 9]); // -> 9534330