Here is sometime I do a lot in PHP. Searching for a needle in a haystack.
$names = [
'Mike',
'John',
'Dave',
'Tony'
];
$gotDave = in_array('Dave', $names);
The runtime of in_array is O(n) where n is the number of elements.
I often setup my lookup data structure to look like this.
$names = [
'Mike' => true,
'John' => true,
'Dave' => true,
'Tony' => true
];
$gotDave = isset($names['Dave']);
The runtime is O(1) because in php the associative array is a hashmap.
Some questions:
Yes, that's a great solution. In fact, that is how Sets are implemented in the core libraries of most programming languages - Off the top of my head, Python, Ruby, and Java do them this way. The Go language doesn't provide a Set, and just tells you to do what you've done.
I can't think of any reason to use any value other than true ```true``. It just makes sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With