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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。