2154. Keep Multiplying Found Values by Two #2440
-
|
Topics: You are given an array of integers You then do the following steps:
Return the final value of Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to repeatedly check if the current value of Approach:
Let's implement this solution in PHP: 2154. Keep Multiplying Found Values by Two <?php
/**
* @param Integer[] $nums
* @param Integer $original
* @return Integer
*/
function findFinalValue($nums, $original) {
$set = array_flip($nums);
while (isset($set[$original])) {
$original *= 2;
}
return $original;
}
// Test cases
echo findFinalValue([5,3,6,1,12], 3) . "\n"; // Output: 24
echo findFinalValue([2,7,9], 4) . "\n"; // Output: 4
echo findFinalValue([1,2,3], 10) . "\n"; // Output: 10
?>Explanation:
This approach efficiently checks for the existence of |
Beta Was this translation helpful? Give feedback.
We need to repeatedly check if the current value of
originalexists in the given arraynums. If it does, we doubleoriginaland continue checking. This process stops whenoriginalis no longer found innums.Approach:
numsinto a set for O(1) average time complexity lookups.originalexists in the set. If it does, doubleoriginaland repeat the process. If not, return the current value oforiginal.Let's implement this solution in PHP: 2154. Keep Multiplying Found Values by Two