Coding Test/LeetCode

[LeetCode] 1929. Concatenation of Array c++

owls 2022. 10. 10. 13:10
728x90
  • 문제

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.

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]

 

  • 문제 해결
class Solution {
public:
    vector<int> getConcatenation(vector<int>& nums) {
        vector<int> answer(nums);
        for(const auto &it : nums){
            answer.push_back(it);
        }
        
        nums.assign(answer.begin(), answer.end());
        return answer;
        }
    
};

다른 풀이

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;
    }
};
728x90