`here I am writing a solution for concatenation of two arrays using but I come up with two solutions. the problems is given as below: 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:
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]
Now,can anyone please explain me how can the space complexity of code (1) is better than that of the code (2)? Both solutions are made by me But I can't understand that how can be the time complexity of code (1) is better that of code (2). please explain this if you know how is code (1) better and taking less memory as compared to that of (2)? code (1) is taking memory of : 44.42 MB. code (2) is taking memory of : 44.72 MB. code(1) :
` class Solution { public int[] getConcatenation(int[] nums) {
int n = nums.length;
int[] arr = new int[2*n];
int k = 0;
int count = 0;
for(int i = 0; i < n; i++){
arr[k] = nums[i];
k++;
if(i == n-1){
i = -1;
count++;
}
if(count == 2){
break;
}
}
return arr;
} }
code (2) :
class Solution {
public int[] getConcatenation(int[] nums) {
int n = nums.length;
int[] arr = new int[2*n];
for(int i = 0; i < 2*n; i++){
arr[i] = nums[i % n];
}
return arr; } }` Ask Question