LeetCode 题解工作台

数组串联

给你一个长度为 n 的整数数组 nums 。请你构建一个长度为 2n 的答案数组 ans ,数组下标 从 0 开始计数 ,对于所有 0 的 i ,满足下述所有要求: ans[i] == nums[i] ans[i + n] == nums[i] 具体而言, ans 由两个 nums 数组 串联 形成…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·模拟

bolt

答案摘要

我们直接根据题目描述模拟,将 中的元素依次添加到答案数组中,然后再将 中的元素再次添加到答案数组中。 时间复杂度 ,空间复杂度 。其中 为数组 的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个长度为 n 的整数数组 nums 。请你构建一个长度为 2n 的答案数组 ans ,数组下标 从 0 开始计数 ,对于所有 0 <= i < ni ,满足下述所有要求:

  • ans[i] == nums[i]
  • ans[i + n] == nums[i]

具体而言,ans 由两个 nums 数组 串联 形成。

返回数组 ans

 

示例 1:

输入:nums = [1,2,1]
输出:[1,2,1,1,2,1]
解释:数组 ans 按下述方式形成:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]

示例 2:

输入:nums = [1,3,2,1]
输出:[1,3,2,1,1,3,2,1]
解释:数组 ans 按下述方式形成:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]

 

提示:

  • n == nums.length
  • 1 <= n <= 1000
  • 1 <= nums[i] <= 1000
lightbulb

解题思路

方法一:模拟

我们直接根据题目描述模拟,将 nums\textit{nums} 中的元素依次添加到答案数组中,然后再将 nums\textit{nums} 中的元素再次添加到答案数组中。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为数组 nums\textit{nums} 的长度。

1
2
3
4
class Solution:
    def getConcatenation(self, nums: List[int]) -> List[int]:
        return nums + nums
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    The candidate should demonstrate an understanding of basic array manipulation.

  • question_mark

    Look for familiarity with Python list operations, like concatenation or replication.

  • question_mark

    Candidates may try to optimize space by simulating the process in-place.

warning

常见陷阱

外企场景
  • error

    Not considering edge cases such as very small arrays or arrays with repeating elements.

  • error

    Over-complicating the solution with unnecessary operations.

  • error

    Not optimizing space usage when memory constraints are part of the interview context.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Create a solution with in-place operations (no additional space used).

  • arrow_right_alt

    Modify the solution to handle larger inputs efficiently.

  • arrow_right_alt

    Consider alternative programming languages and their array manipulation capabilities.

help

常见问题

外企场景

数组串联题解:数组·模拟 | LeetCode #1929 简单