Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Write a function that finds a triplet from an array that sum to a given value.
- // Complexity: O(n2)
- function findTriplet($array, $sum)
- {
- if (count($array) < 3) return null;
- for ($i = 0; $i < count($array) - 2; $i++) {
- $firstItem = $array[$i];
- $seenList = [];
- for ($j = $i + 1; $j < count($array); $j++) {
- $thirdItem = $array[$j];
- $secondItem = $sum - ($firstItem + $thirdItem);
- if (isset($seenList[$secondItem])) {
- return [$firstItem, $secondItem, $thirdItem];
- }
- $seenList[$thirdItem] = '';
- }
- }
- return null;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement