Leetcode Problem 1847. Closest Room

1847. Closest Room

Leetcode Solutions

Sort Queries and Use TreeSet for Efficient Room ID Retrieval

  1. Sort the rooms array in descending order based on room size.
  2. Sort the queries array in descending order based on the minimum size required, and keep track of the original indices.
  3. Initialize a TreeSet/SortedList to keep track of room IDs that meet the minimum size requirement.
  4. Iterate through the sorted queries, and for each query: a. Add all room IDs to the TreeSet/SortedList that have not been added yet and have a size greater than or equal to the current query's minimum size. b. Find the closest room ID to the preferred ID by checking the floor and ceiling in the TreeSet/SortedList. c. Choose the room with the smaller ID if there is a tie in the absolute difference. d. If no room meets the criteria, return -1 for that query.
  5. Return the results in the order of the original queries.
UML Thumbnail

Brute Force Search with Sorting

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...