Press "Enter" to skip to content

Posts tagged as “hashtable”

花花酱 LeetCode 2349. Design a Number Container System

两个hashtable,一个是index->number,另外一个是number -> {index},使用treeset,自动排序。

时间复杂度:change O(logn),find O(1)
空间复杂度:O(n)

花花酱 LeetCode 2353. Design a Food Rating System

Hashtable + TreeSet / OrderedSet

用了三个Hashtable…

  1. 菜名 -> 菜系
  2. 菜系 -> Treemap
  3. 菜名 -> 所在Treemap中的迭代器

每个菜系用一个TreeSet来保存从高到低的菜色排名,查询的时候只要拿出第一个就好了。

修改的时候,拿出迭代器,删除原来的评分,再把新的评分加入(别忘了更新迭代器)

时间复杂度:构造O(nlogn),修改O(logn),查询O(1)

空间复杂度:O(n)

花花酱 LeetCode 3242. Design Neighbor Sum Service

青铜 Brute Force:每次需要花费O(n*n)的时间去查找query所在的格子,求和是O(1)。总的时间复杂度达到O(n^4),肯定会超时。

白银 Hashtable:由于所有元素的值的唯一的,我们可以使用hashtable(或者数组)来记录value所在的格子坐标,这样每次Query都是O(1)时间。
时间复杂度:初始化O(n^2),query O(1)。
空间复杂度:O(n^2)

黄金 Precompute:在初始化的时候顺便求合,开两个数组一个存上下左右的,一个存对角线的。query的时候直接返回答案就可以了。
时间复杂度和白银是一样的,但会快一些(省去了求合的过程)。

花花酱 LeetCode 3408. Design Task Manager

  1. pq_ 使用std::map充当优先队列,存储(priority, taskId) -> userId
  2. m_ 使用std::unordered_map,存储taskId -> pq_的迭代器

所有操作都是O(logn)

花花酱 LeetCode 3005. Count Elements With Maximum Frequency

You are given an array nums consisting of positive integers.

Return the total frequencies of elements in nums such that those elements all have the maximum frequency.

The frequency of an element is the number of occurrences of that element in the array.

Example 1:

Input: nums = [1,2,2,3,1,4]
Output: 4
Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array.
So the number of elements in the array with maximum frequency is 4.

Example 2:

Input: nums = [1,2,3,4,5]
Output: 5
Explanation: All elements of the array have a frequency of 1 which is the maximum.
So the number of elements in the array with maximum frequency is 5.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100

Solution: Hashtable

Use a hashtable to store the frequency of each element, and compare it with a running maximum frequency. Reset answer if current frequency is greater than maximum frequency. Increment the answer if current frequency is equal to the maximum frequency.

Time complexity: O(n)
Space complexity: O(n)

C++

// Author: Huahua