--- layout: post title: Leetcode - Concatenation of array(1929) date: '2022-11-19 08:43:07 +0800' categories: [Code, C] tags: [c, leetcode] # TAG names should always be lowercase author: devoalda math: true libraries: - mathjax math: true --- # Introduction 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 ```shell 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] ``` # Process This was a pretty simple one other that figuring out how to use `malloc` again. This would be much simpler to do in python. After creating an array with size dynamically allocated to `2n` where `n` is the size of the input array, I've managd to follow the description and concatenate the array using a for loop. There should probably be a more elegant and efficient way to do this, but I'll still need to learn more about pointers and arrays. # Code ```c /** * Note: The returned array must be malloced, assume caller calls free(). */ int* getConcatenation(int* nums, int numsSize, int* returnSize){ //int n = (sizeof(nums)/sizeof(int)); int *ans = (int *)malloc(2 * numsSize * sizeof(int)); int i; for (i = 0; i