LeetCode Biweekly Contest 51
| Rank | Name | Score | Finish Time | Q1 (3) | Q2 (4) | Q3 (5) | Q4 (6) |
|---|---|---|---|---|---|---|---|
| 150 / 9378 | YoungForest | 18 | 0:32:04 | 0:05:26 | 0:07:22 | 0:11:24 | 0:32:04 |
A hand-speed contest. Recently my hand speed is far worse than before, and the last problem also took quite a bit of time because I was not familiar enough with it.
Actually, in a hand-speed contest, the algorithms for all problems are not hard. Thinking of the correct solution is quick, but implementing it quickly and bug-free tests every programmer’s fundamentals.
1844. Replace All Digits with Characters
A warm-up problem. Just follow the problem statement.
1 | class Solution { |
Time complexity: O(N),
space complexity: O(1).
1845. Seat Reservation Manager
Because each operation finds the smallest seat number, and there is also an insert (unreserve) operation, it is obvious that a priority_queue / Heap is needed to implement this requirement.
1 | class SeatManager { |
Time complexity:
- SeatManager: O(n),
- reserve: O(log n),
- unreserve: O(log n).
Space complexity: O(n).
1846. Maximum Element After Decreasing and Rearranging
Greedy.
Observing the two operations, Decrease and Rearrange, we can see that actually only one Rearrange is needed. When doing Decrease, prioritize reducing smaller values. Because larger values can always cover smaller ones after decreasing, but smaller values cannot do the reverse.
1 | class Solution { |
Time complexity: O(n log n + n),
space complexity: O(1).
1847. Closest Room
The first thought is a brute-force solution: for each query, traverse all rooms once to find the answer. The time complexity is O(k * n), which will obviously TLE.
The intended solution should have a form like O(n log n).
Here we need a so-called offline query technique.
Online computation means the answer order of queries is unchanged, similar to a function that is called once and answers once.
Offline computation means the answer order of queries can be changed, and an array of queries needs to be solved all at once. At this time, we can reorder queries to get an amortized faster algorithm.
First, sort queries by minisize, and sort rooms by size.
Use two pointers to ensure that for the current query, all rooms satisfying the requirement have been added to the candidate set. Here we use a TreeSet to maintain the candidate set, so the nearest room can be searched in log n.
1 | class Solution { |
Time complexity: O(n log n + k log n + k log k),
space complexity: O(k + n).