194,344 views
37 votes
37 votes
How do I do this?

Given an integer array nums, return a new array with a length of nums.length*2 where each element in nums appears twice in a row.
doubleElements([2, 3, 5, 4]) → [2, 2, 3, 3, 5, 5, 4, 4]
doubleElements([1, 2, 2, 3, 4, 4, 5, 6]) → [1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6]
doubleElements([1, 2, 3, 4, 5, 6]) → [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]

I was given the layout of how the code would look but I'm baffled on what to put in the ??? that will return an array that has a duplicate of a previous element.
ex: [2,3] = [2,2,3,3]

public int[] doubleElements(int[] nums){
int[] ans = new int[nums.length*2];
for(int i = 0; i < nums.length; i++){
ans[??] = nums[i];
ans[??] = nums[i];
}
return ans;
}

User Michal Boska
by
3.0k points

1 Answer

5 votes
5 votes

import java.util.*;

class DMatrix {

public static void doubleElements(int[] nums) {

int[] ans = new int[nums.length*2];

for(int i = 1; i <= nums.length; i++){

ans[(2*i)-2] = nums[i-1];

ans[(2*i)-1] = nums[i-1];

}

for(int j=0; j<ans.length;j++) {

System.out.print(ans[j] + ", ");

}

}

public static void main(String[] args) {

int[] MyNums = {1,1,3,55,7,7,7,10};

doubleElements(MyNums);

}

}

How do I do this? Given an integer array nums, return a new array with a length of-example-1
User Chris Xue
by
2.7k points