Design Movie Rental System LeetCode solution in Java

1
class MovieRentingSystem {
2

3
Map<Integer, Map<Integer, Pair>> map = new HashMap<>();
4

5
TreeSet<Pair> rented = new TreeSet<>(new rcomp());
6

7
public MovieRentingSystem(int n, int[][] entries) {
8
for (int entry[] : entries) {
9
Map<Integer, Pair> map1 = map.getOrDefault(entry[1], new HashMap<>());
10
Pair p = new Pair(entry[0], entry[1], entry[2]);
11
map1.put(entry[0], p);
12
map.put(entry[1], map1);
13
}
14
}
15

16
public List<Integer> search(int movie) {
17

18
PriorityQueue<Pair> pq = new PriorityQueue<>(new scomp());
19

20
Map<Integer, Pair> map1 = map.getOrDefault(movie, new HashMap<>());
21

22
for (Pair p : map1.values()) {
23
if (p.rent == true) {
24
continue;
25
}
26
if (pq.size() < 5) {
27
pq.add(p);
28
} else {
29
if (pq.peek().price > p.price) {
30
pq.poll();
31
pq.add(p);
32
} else if (pq.peek().price == p.price && pq.peek().shop > p.shop) {
33
pq.poll();
34
pq.add(p);
35
}
36
}
37
}
38

39
List<Integer> ans = new ArrayList<>();
40

41
while (!pq.isEmpty()) {
42

43
Pair p = pq.poll();
44
ans.add(0, p.shop);
45
}
46

47
return ans;
48
}
49

50
public void rent(int shop, int movie) {
51

52
Pair p = map.get(movie).get(shop);
53
p.rent = true;
54
rented.add(p);
55
}
56

57
public void drop(int shop, int movie) {
58
Pair p = map.get(movie).get(shop);
59
p.rent = false;
60
rented.remove(p);
61
}
62

63
public List<List<Integer>> report() {
64
List<List<Integer>> ans = new ArrayList<>();
65

66
for (Pair p : rented) {
67
List<Integer> t = new ArrayList<>();
68
t.add(p.shop);
69
t.add(p.movie);
70
ans.add(t);
71
if (ans.size() == 5) {
72
break;
73
}
74
}
75

76
return ans;
77
}
78
}
79

80
class scomp implements Comparator<Pair> {
81

82
public int compare(Pair a, Pair b) {
83
if (a.price == b.price) {
84
return b.shop - a.shop;
85
}
86
return b.price - a.price;
87
}
88
}
89

90
class rcomp implements Comparator<Pair> {
91
public int compare(Pair a, Pair b) {
92
if (a.price == b.price) {
93
if (a.shop == b.shop) {
94
return a.movie - b.movie;
95
}
96
return a.shop - b.shop;
97
}
98
return a.price - b.price;
99
}
100
}
101

102
class Pair {
103

104
int shop;
105
int movie;
106
int price;
107
boolean rent;
108

109
Pair(int shop, int movie, int price) {
110
this.shop = shop;
111
this.movie = movie;
112
this.price = price;
113
this.rent = false;
114
}
115

116
public int hashCode() {
117
return Objects.hash(shop, movie, price);
118
}
119

120
public boolean equals(Object obj) {
121
Pair obj1 = (Pair) obj;
122
if (obj1.shop == shop && obj1.movie == movie && obj1.price == price) {
123
return true;
124
}
125
return false;
126
}
127
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0