Leetcode 1929. Concatenation of Array
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. Specifically, ans should be a concatenation of nums followed by nums. Return the array ans.
Example:
Input: nums = [1, 2, 1]
Output: [1, 2, 1, 1, 2, 1]
nums be an empty array?
nums will have at least one element.nums?
To solve this problem, we need to accomplish two key steps:
2n.ans array with the elements of nums.ans array with the elements of nums again.This can be done using a simple loop to copy elements from nums to the ans array at appropriate positions.
#include <vector>
using namespace std;
vector<int> getConcatenation(vector<int>& nums) {
int n = nums.size();
vector<int> ans(2 * n); // Create a result array of size 2*n
// Fill the first half and the second half
for (int i = 0; i < n; ++i) {
ans[i] = nums[i];
ans[i + n] = nums[i];
}
return ans;
}
// Example usage:
// int main() {
// vector<int> nums = {1, 2, 1};
// vector<int> result = getConcatenation(nums);
//
// for (int val : result) {
// cout << val << " ";
// }
// return 0;
// }
nums exactly twice to fill up ans.ans.This ensures that the solution is efficient with respect to both time and space for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?