LeetCode 题解工作台

基于排列构建数组

给你一个 从 0 开始的排列 nums ( 下标也从 0 开始 )。请你构建一个 同样长度 的数组 ans ,其中,对于每个 i ( 0 ),都满足 ans[i] = nums[nums[i]] 。返回构建好的数组 ans 。 从 0 开始的排列 nums 是一个由 0 到 nums.length …

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·模拟

bolt

答案摘要

我们可以直接模拟题目描述的过程,构建一个新的数组 ,对于每个 ,令 $\textit{ans}[i] = \textit{nums}[\textit{nums}[i]]$。 时间复杂度 ,其中 是数组 的长度。忽略答案数组的空间消耗,空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 从 0 开始的排列 nums下标也从 0 开始)。请你构建一个 同样长度 的数组 ans ,其中,对于每个 i0 <= i < nums.length),都满足 ans[i] = nums[nums[i]] 。返回构建好的数组 ans

从 0 开始的排列 nums 是一个由 0 到 nums.length - 10nums.length - 1 也包含在内)的不同整数组成的数组。

 

示例 1:

输入:nums = [0,2,1,5,3,4]
输出:[0,1,2,4,5,3]
解释:数组 ans 构建如下:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
    = [0,1,2,4,5,3]

示例 2:

输入:nums = [5,0,1,2,3,4]
输出:[4,5,0,1,2,3]
解释:数组 ans 构建如下:
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
    = [4,5,0,1,2,3]

 

提示:

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] < nums.length
  • nums 中的元素 互不相同

 

进阶:你能在不使用额外空间的情况下解决此问题吗(即 O(1) 内存)?

lightbulb

解题思路

方法一:模拟

我们可以直接模拟题目描述的过程,构建一个新的数组 ans\textit{ans},对于每个 ii,令 ans[i]=nums[nums[i]]\textit{ans}[i] = \textit{nums}[\textit{nums}[i]]

时间复杂度 O(n)O(n),其中 nn 是数组 nums\textit{nums} 的长度。忽略答案数组的空间消耗,空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def buildArray(self, nums: List[int]) -> List[int]:
        return [nums[num] for num in nums]
speed

复杂度分析

指标
时间O(n)
空间O(1)
psychology

面试官常问的追问

外企场景
  • question_mark

    Does the candidate directly simulate the process described in the statement?

  • question_mark

    Does the candidate maintain O(1) space complexity in their solution?

  • question_mark

    Does the candidate handle edge cases and large input sizes correctly?

warning

常见陷阱

外企场景
  • error

    Confusing the problem with a more complex array manipulation task, forgetting to follow the direct simulation approach.

  • error

    Using extra space beyond O(1), which violates the problem’s constraints on space efficiency.

  • error

    Overlooking edge cases such as very small or very large arrays, causing the solution to fail in certain scenarios.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Modify the problem to handle multi-dimensional arrays.

  • arrow_right_alt

    Consider implementing a more complex simulation with different mapping rules.

  • arrow_right_alt

    Increase the size of the array significantly, ensuring the solution scales efficiently.

help

常见问题

外企场景

基于排列构建数组题解:数组·模拟 | LeetCode #1920 简单