← 返回 snowflake 的题目列表K Top Selling Books
类型:qbank
Design a data structure that tracks cumulative book sales and returns the top sellers after each update.
Tracking Top Selling Books
We need to build a system that keeps track of total book sales. It should also give us a list of the top-selling books every time we update the sales data.
Class Requirements
You need to implement the BestSellerTracker class with the following methods:
BestSellerTracker(): Sets up the tracker with no sales data initially.
List<String> bestSellers(Map<String, Integer> sales, Integer k): Adds new sales numbers to the existing totals for each book. After updating the totals, it returns the top k book titles.
Ranking Rules
Sort the books using this order:
Sales Count: Books with higher total sales come first.
Alphabetical Order: If two books have the exact same sales total, pick the title that is "larger" alphabetically (for example, "beta" comes before "alpha").
Note: If the requested k is bigger than the total number of books tracked, simply return all the books in the correct order.
Sample Cases
Case 1:
Input: ["BestSellerTracker","bestSellers","bestSellers"] [[],[{"a":5,"b":10,"c":15},2],[{"a":20,"b":20,"c":5},2]]
Output: [null,["c","b"],["b","a"]]
Breakdown:
First Update: We add sales {a:5, b:10, c:15}. The totals are now {a:5, b:10, c:15}. The top 2 books are "c" (15) and "b" (10).
Second Update: We add more sales {a:20, b:20, c:5} to the old totals.
Book "a": 5 + 20 = 25
Book "b": 10 + 20 = 30
Book "c": 15 + 5 = 20
New totals are {a:25, b:30, c:20}. The top 2 are now "b" (30) and "a" (25).
Case 2:
Input: ["BestSellerTracker","bestSellers"] [[],[{"alpha":4,"beta":4,"gamma":1},5]]
Output: [null,["beta","alpha","gamma"]]
Breakdown: "alpha" and "beta" are tied with 4 sales each. Since "beta" is alphabetically larger than "alpha", "beta" is placed first.
Technical Limits
0 <= sales.size() <= 10^4
0 <= sales[title] <= 10^6
1 <= title.length <= 100
1 <= k <= 10^4
The bestSellers method will be called at most 10^4 times.