LeetCode 题解工作台

转换数组

给你一个整数数组 nums ,它表示一个循环数组。请你遵循以下规则创建一个大小 相同 的新数组 result : 对于每个下标 i (其中 0 ),独立执行以下操作: 如果 nums[i] > 0 :从下标 i 开始,向 右 移动 nums[i] 步,在循环数组中落脚的下标对应的值赋给 result…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·模拟

bolt

答案摘要

我们创建一个结果数组 ,对于每个下标,根据 的正负向右或向左移动 步,计算出落脚的下标,并将该下标对应的值赋给 。 时间复杂度 ,空间复杂度 。其中 是数组 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·模拟 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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
lightbulb

解题思路

方法一:模拟

我们创建一个结果数组 ans\textit{ans},对于每个下标,根据 nums[i]nums[i] 的正负向右或向左移动 nums[i]|nums[i]| 步,计算出落脚的下标,并将该下标对应的值赋给 ans[i]\textit{ans}[i]

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是数组 numsnums 的长度。

1
2
3
4
5
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)]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

转换数组题解:数组·模拟 | LeetCode #3379 简单