LeetCode 题解工作台
转换数组
给你一个整数数组 nums ,它表示一个循环数组。请你遵循以下规则创建一个大小 相同 的新数组 result : 对于每个下标 i (其中 0 ),独立执行以下操作: 如果 nums[i] > 0 :从下标 i 开始,向 右 移动 nums[i] 步,在循环数组中落脚的下标对应的值赋给 result…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·模拟
答案摘要
我们创建一个结果数组 ,对于每个下标,根据 的正负向右或向左移动 步,计算出落脚的下标,并将该下标对应的值赋给 。 时间复杂度 ,空间复杂度 。其中 是数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路
题目描述
给你一个整数数组 nums,它表示一个循环数组。请你遵循以下规则创建一个大小 相同 的新数组 result :
i(其中 0 <= i < nums.length),独立执行以下操作:
- 如果
nums[i] > 0:从下标i开始,向 右 移动nums[i]步,在循环数组中落脚的下标对应的值赋给result[i]。 - 如果
nums[i] < 0:从下标i开始,向 左 移动abs(nums[i])步,在循环数组中落脚的下标对应的值赋给result[i]。 - 如果
nums[i] == 0:将nums[i]的值赋给result[i]。
返回新数组 result。
注意:由于 nums 是循环数组,向右移动超过最后一个元素时将回到开头,向左移动超过第一个元素时将回到末尾。
示例 1:
输入: nums = [3,-2,1,1]
输出: [1,1,1,3]
解释:
- 对于
nums[0]等于 3,向右移动 3 步到nums[3],因此result[0]为 1。 - 对于
nums[1]等于 -2,向左移动 2 步到nums[3],因此result[1]为 1。 - 对于
nums[2]等于 1,向右移动 1 步到nums[3],因此result[2]为 1。 - 对于
nums[3]等于 1,向右移动 1 步到nums[0],因此result[3]为 3。
示例 2:
输入: nums = [-1,4,-1]
输出: [-1,-1,4]
解释:
- 对于
nums[0]等于 -1,向左移动 1 步到nums[2],因此result[0]为 -1。 - 对于
nums[1]等于 4,向右移动 4 步到nums[2],因此result[1]为 -1。 - 对于
nums[2]等于 -1,向左移动 1 步到nums[1],因此result[2]为 4。
提示:
1 <= nums.length <= 100-100 <= nums[i] <= 100
解题思路
方法一:模拟
我们创建一个结果数组 ,对于每个下标,根据 的正负向右或向左移动 步,计算出落脚的下标,并将该下标对应的值赋给 。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def constructTransformedArray(self, nums: List[int]) -> List[int]:
n = len(nums)
return [nums[(i + x % n + n) % n] for i, x in enumerate(nums)]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates a solid understanding of array indexing and modular arithmetic.
- question_mark
The candidate can effectively simulate circular array behavior with minimal memory usage.
- question_mark
The candidate can write a time-efficient solution while correctly handling circular array traversal.
常见陷阱
外企场景- error
Not using modular arithmetic correctly to handle the circular indexing.
- error
Overcomplicating the solution with unnecessary data structures.
- error
Failing to account for the circular nature of the array, causing incorrect mappings in the result array.
进阶变体
外企场景- arrow_right_alt
Simulating different transformations based on different rules while keeping the array circular.
- arrow_right_alt
Handling different array sizes, such as large inputs beyond the typical size constraints.
- arrow_right_alt
Modifying the circular transformation rules, such as shifting values based on additional constraints.