[array]1929. Concatenation of Array

1929. Concatenation of Array

Description :
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).
Specifically, ans is the concatenation of two nums arrays.
Return the array ans.

Example 1:
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:

  • ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
  • ans = [1,2,1,1,2,1]
    Example 2:
    Input: nums = [1,3,2,1]
    Output: [1,3,2,1,1,3,2,1]
    Explanation: The array ans is formed as follows:
  • 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]

Constraints:

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

Hint 1
Build an array of size 2 * n and assign num[i] to ans[i] and ans[i + n]

solution1 按要求串联

思路与算法

我们顺序遍历修改前 \textit{nums}nums 数组的元素,并按顺序添加至 \textit{nums}nums 数组的尾部。最终,修改后的 \textit{nums}nums 数组即为串联形成的数组,我们返回该数组作为答案。

对于 \texttt{Python}Python 语言,我们可以直接使用 \texttt{list}list 的 \textit{extend}()extend() 方法实现串联操作。

class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; ++i){
            nums.push_back(nums[i]);
        }
return nums;
    }
};

复杂度分析

时间复杂度:O(n)O(n),其中 nn 为 \textit{nums}nums 的长度。即为遍历与串联的时间复杂度。

空间复杂度:O(1)O(1),输出数组不计入空间复杂度。

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/concatenation-of-array/solution/shu-zu-chuan-lian-by-leetcode-solution-wejh/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

solution 2

class Solution {
public:
vector getConcatenation(vector& nums) {
nums.insert(nums.end(), nums.begin(), nums.end());
return nums;
}
};

作者:liu-yong-qi
链接:https://leetcode.cn/problems/concatenation-of-array/solution/1-xing-dai-ma-by-liu-yong-qi-bo1o/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值