Design a system that stores numbers in "containers" (indexed slots) and supports two main operations:
1.change(index, number):
Set the container at the specified index to the given number. If a container already has a number, replace it with the new number.
-1
.change(index, number)
, the system stores number
at that index. If the container already held a number, it is replaced.find(number)
, the system searches for all containers containing that number and returns the smallest index among them. If none is found, it returns -1
.Input:
["NumberContainers", "change", "change", "find", "change", "find"] [[], [2, 10], [5, 10], [10], [2, 20], [10]]
Expected Output:
[null, null, null, 2, null, 5]
Step-by-Step Explanation:
change(2, 10)
change(5, 10)
find(10)
2
change(2, 20)
find(10)
5
Input:
["NumberContainers", "change", "find", "change", "change", "find", "change", "find", "find"] [[], [3, 15], [15], [7, 15], [3, 20], [15], [7, 30], [15], [20]]
Expected Output:
[null, null, 3, null, null, 7, null, -1, 3]
Step-by-Step Explanation:
change(3, 15)
find(15)
3
change(7, 15)
change(3, 20)
find(15)
7
change(7, 30)
find(15)
-1
find(20)
3
1 <= index, number <= 10^9
10^5
calls combined to the change
and find
operations.https://leetcode.com/problems/design-a-number-container-system/description
Loading component...
Loading component...
Main Function is not defined.
INPUT : ["NumberContainers", "change", "change", "find", "change", "find"] [[], [2, 10], [5, 10], [10], [2, 20], [10]]
Output: [null, null, null, 2, null, 5]
public static void change(int index, int number) {
if (indexMap.containsKey(index)) {
int oldNumber = indexMap.get(index);
if (numToIndices.containsKey(oldNumber)) {
numToIndices.get(oldNumber).remove(index);
}//If End
}//If End
indexMap.put(index, number);
numToIndices.putIfAbsent(number, new TreeSet<>());
numToIndices.get(number).add(index);
}//function end
public static int find(int number) {
if (!numToIndices.containsKey(number) || numToIndices.get(number).isEmpty()) {
return -1;
}
return numToIndices.get(number).first();
}//function end