-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path381.php
59 lines (56 loc) · 1.42 KB
/
381.php
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
class RandomizedCollection
{
private $arr;
private $len;
private $indexMap;
/**
* Initialize your data structure here.
*/
public function __construct()
{
$this->len = -1;
$this->arr = [];
}
/**
* Inserts a value to the collection. Returns true if the collection did not already contain the specified element.
* @param Integer $val
* @return Boolean
*/
public function insert($val)
{
$this->len++;
$this->arr[] = $val;
if (!isset($this->indexMap[$val])) {
$this->indexMap[$val] = [$this->len];
return true;
}
array_push($this->indexMap[$val], $this->len);
return false;
}
/**
* Removes a value from the collection. Returns true if the collection contained the specified element.
* @param Integer $val
* @return Boolean
*/
public function remove($val)
{
if (isset($this->indexMap[$val])) {
$index = array_pop($this->indexMap[$val]);
if (empty($this->indexMap[$val])) {
unset($this->indexMap[$val]);
}
unset($this->arr[$index]);
return true;
}
return false;
}
/**
* Get a random element from the collection.
* @return Integer
*/
public function getRandom()
{
return $this->arr[array_rand($this->arr)];
}
}