2349. Design a Number Container System #1287
-
Topics: Design a number container system that can do the following:
Implement the
Example 1:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to design a number container system that allows efficient insertion or replacement of numbers at specific indices and retrieval of the smallest index for a given number. The solution must handle these operations efficiently even with a large number of indices and numbers. ApproachThe approach involves using two main data structures:
Steps:
Let's implement this solution in PHP: 2349. Design a Number Container System <?php
class NumberContainers {
private $indexToNumber;
private $numberToHeap;
/**
*/
function __construct() {
$this->indexToNumber = array();
$this->numberToHeap = array();
}
/**
* @param Integer $index
* @param Integer $number
* @return NULL
*/
function change($index, $number) {
// Check if the index already has a number and it's the same as the new number
if (isset($this->indexToNumber[$index]) && $this->indexToNumber[$index] === $number) {
return;
}
// Update the index's number
$this->indexToNumber[$index] = $number;
// Add the index to the new number's heap
if (!isset($this->numberToHeap[$number])) {
$this->numberToHeap[$number] = new SplMinHeap();
}
$this->numberToHeap[$number]->insert($index);
}
/**
* @param Integer $number
* @return Integer
*/
function find($number) {
if (!isset($this->numberToHeap[$number])) {
return -1;
}
$heap = $this->numberToHeap[$number];
while (!$heap->isEmpty()) {
$index = $heap->top();
// Check if the current number at this index matches the target number
if (isset($this->indexToNumber[$index]) && $this->indexToNumber[$index] === $number) {
return $index;
} else {
// Remove the invalid index from the heap
$heap->extract();
}
}
return -1;
}
}
// Example usage:
$nc = new NumberContainers();
echo $nc->find(10) . "\n"; // Output: -1
$nc->change(2, 10);
$nc->change(1, 10);
$nc->change(3, 10);
$nc->change(5, 10);
echo $nc->find(10) . "\n"; // Output: 1
$nc->change(1, 20);
echo $nc->find(10) . "\n"; // Output: 2
?> Explanation:
This approach ensures efficient handling of both operations, with the change operation in O(log n) time (due to heap insertion) and the find operation efficiently removing invalid indices in O(log n) time for each removal, ensuring optimal performance for large datasets. |
Beta Was this translation helpful? Give feedback.
We need to design a number container system that allows efficient insertion or replacement of numbers at specific indices and retrieval of the smallest index for a given number. The solution must handle these operations efficiently even with a large number of indices and numbers.
Approach
The approach involves using two main data structures: