-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPriorityQueues.java
63 lines (53 loc) Β· 1.55 KB
/
PriorityQueues.java
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
package day10;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class PriorityQueues {
/*
inserting: O(log(n))
retrieving: O(log(n))
*/
public static void main(String[] args) {
Queue<Rectangle> queue = new PriorityQueue<>(Comparator
.comparing(Rectangle::getLength)
.thenComparing(Rectangle::getBreadth)
);
queue.add(new Rectangle(10, 4));
queue.add(new Rectangle(10, 90));
queue.add(new Rectangle(20, 4));
queue.add(new Rectangle(10, 34));
queue.add(new Rectangle(1, 0));
queue.add(new Rectangle(4, 34));
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
static class Rectangle implements Comparable<Rectangle> {
int breadth;
int length;
Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getLength() {
return length;
}
public int getBreadth() {
return breadth;
}
@Override
public int compareTo(Rectangle other) {
return Integer.compare(
this.length * this.breadth,
other.length * other.breadth
);
}
@Override
public String toString() {
return "Rectangle{" +
"breadth=" + breadth +
", length=" + length +
'}';
}
}
}