LeetCode 题解工作台
将找到的值乘以 2
给你一个整数数组 nums ,另给你一个整数 original ,这是需要在 nums 中搜索的第一个数字。 接下来,你需要按下述步骤操作: 如果在 nums 中找到 original ,将 original 乘以 2 ,得到新 original (即,令 original = 2 * origin…
4
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 记录数组 中的所有数字。 接下来,我们从 开始,如果 在 中,我们将 乘以 ,直到 不在 中,返回 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums ,另给你一个整数 original ,这是需要在 nums 中搜索的第一个数字。
接下来,你需要按下述步骤操作:
- 如果在
nums中找到original,将original乘以 2 ,得到新original(即,令original = 2 * original)。 - 否则,停止这一过程。
- 只要能在数组中找到新
original,就对新original继续 重复 这一过程。
返回 original 的 最终 值。
示例 1:
输入:nums = [5,3,6,1,12], original = 3 输出:24 解释: - 3 能在 nums 中找到。3 * 2 = 6 。 - 6 能在 nums 中找到。6 * 2 = 12 。 - 12 能在 nums 中找到。12 * 2 = 24 。 - 24 不能在 nums 中找到。因此,返回 24 。
示例 2:
输入:nums = [2,7,9], original = 4 输出:4 解释: - 4 不能在 nums 中找到。因此,返回 4 。
提示:
1 <= nums.length <= 10001 <= nums[i], original <= 1000
解题思路
方法一:哈希表
我们用一个哈希表 记录数组 中的所有数字。
接下来,我们从 开始,如果 在 中,我们将 乘以 ,直到 不在 中,返回 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def findFinalValue(self, nums: List[int], original: int) -> int:
s = set(nums)
while original in s:
original <<= 1
return original
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Can the candidate optimize array lookups using hash sets?
- question_mark
Is the candidate comfortable with iterative problem-solving techniques?
- question_mark
How well does the candidate handle the trade-off between time and space complexity?
常见陷阱
外企场景- error
Not using a hash set to optimize the search operation.
- error
Missing edge cases where the original value is never found in the array.
- error
Failing to update the value properly after each multiplication step.
进阶变体
外企场景- arrow_right_alt
What if the array is sorted? Can you optimize the solution further?
- arrow_right_alt
What if the problem involves multiple values to check and multiply?
- arrow_right_alt
How would the solution change if we needed to track the number of iterations?