-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCode_02_Less_Money.java
More file actions
86 lines (71 loc) · 2.21 KB
/
Code_02_Less_Money.java
File metadata and controls
86 lines (71 loc) · 2.21 KB
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
package algorithm.basic07;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @author mood321
* @date 2019/11/11
* @email [email protected]
*/
public class Code_02_Less_Money {
public static int lessMoney(int[] arr) {
if(arr==null){
return 0;
}
PriorityQueue<Integer> minQueue = new PriorityQueue<>();
for (int i : arr) {
minQueue.add(i);
}
int sum=0;
int cur=0;
while(minQueue.size()>1){
cur = minQueue.poll() + minQueue.poll();
sum +=cur;
minQueue.add(cur);
}
return sum;
}
public static class MinheapComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o1 - o2; // < 0 o1 < o2 负数
}
}
public static class MaxheapComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1; // < o2 < o1
}
}
public static void main(String[] args) {
// solution
int[] arr = { 6, 7, 8, 9 };
System.out.println(lessMoney(arr));
int[] arrForHeap = { 3, 5, 2, 7, 0, 1, 6, 4 };
// min heap
PriorityQueue<Integer> minQ1 = new PriorityQueue<>();
for (int i = 0; i < arrForHeap.length; i++) {
minQ1.add(arrForHeap[i]);
}
while (!minQ1.isEmpty()) {
System.out.print(minQ1.poll() + " ");
}
System.out.println();
// min heap use Comparator
PriorityQueue<Integer> minQ2 = new PriorityQueue<>(new MinheapComparator());
for (int i = 0; i < arrForHeap.length; i++) {
minQ2.add(arrForHeap[i]);
}
while (!minQ2.isEmpty()) {
System.out.print(minQ2.poll() + " ");
}
System.out.println();
// max heap use Comparator
PriorityQueue<Integer> maxQ = new PriorityQueue<>(new MaxheapComparator());
for (int i = 0; i < arrForHeap.length; i++) {
maxQ.add(arrForHeap[i]);
}
while (!maxQ.isEmpty()) {
System.out.print(maxQ.poll() + " ");
}
}
}