[LeetCode] Design a Number Container System

2349. Design a Number Container System

Design a number container system that can do the following:

  • Insert or Replace a number at the given index in the system.
  • Return the smallest index for the given number in the system.

Implement the NumberContainers class:

  • NumberContainers() Initializes the number container system.
  • void change(int index, int number) Fills the container at index with the number. If there is already a number at that index, replace it.
  • int find(int number) Returns the smallest index for the given number, or -1 if there is no index that is filled by number in the system.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class NumberContainers {
unordered_map<int, int> mp;
unordered_map<int, set<int>> mmp;
public:
NumberContainers() {}

void change(int index, int number) {
if(mp.count(index)) mmp[mp[index]].erase(index);

mp[index] = number;
mmp[number].insert(index);
}

int find(int number) {
if(mmp[number].empty()) return -1;
return *begin(mmp[number]);
}
};

/**
* Your NumberContainers object will be instantiated and called as such:
* NumberContainers* obj = new NumberContainers();
* obj->change(index,number);
* int param_2 = obj->find(number);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/24/PS/LeetCode/design-a-number-container-system/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.