Input: nums =[5,3,6,1,12], original =3Output: 24Explanation:
-3is found in nums.3is multiplied by 2 to obtain 6.-6is found in nums.6is multiplied by 2 to obtain 12.-12is found in nums.12is multiplied by 2 to obtain 24.-24is not found in nums. Thus,24is returned.
classSolution {
publicintfindFinalValue(int[] nums, int original) {
Set<Integer> s =new HashSet<>();
for (int n : nums) s.add(n);
while (s.contains(original)) original *= 2;
return original;
}
}
1
2
3
4
5
6
7
8
classSolution {
funfindFinalValue(nums: IntArray, original: Int): Int {
val s = nums.toSet()
var ans = original
while (ans in s) ans *=2return ans
}
}
1
2
3
4
5
6
classSolution:
deffindFinalValue(self, nums: list[int], original: int) -> int:
s = set(nums)
while original in s:
original *=2return original
1
2
3
4
5
6
7
8
9
use std::collections::HashSet;
impl Solution {
pubfnfind_final_value(nums: Vec<i32>, original: i32) -> i32 {
let s: HashSet<_>= nums.into_iter().collect();
letmut ans = original;
while s.contains(&ans) { ans *=2; }
ans
}
}
⏰ Time complexity: O(n + logM), where n is the length of nums and M is the maximum value reached. Building the set is O(n), and each multiply/check is O(1).