Array assignment copy concatenation

You are given an integer array nums of length n. Please construct an answer array ans with a length of 2n, the array subscript starts counting from 0, and for all i where 0 <= i < n, satisfy all the following requirements:

  • ans[i] == nums[i]
  • ans[i + n] == nums[i]
    Specifically, ans is formed by concatenating two nums arrays.

Returns the array ans.

Example 1

输入:nums = [1,2,1]
输出:[1,2,1,1,2,1]
解释:数组 ans 按下述方式形成:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]

Example 2

输入:nums = [1,3,2,1]
输出:[1,3,2,1,1,3,2,1]
解释:数组 ans 按下述方式形成:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]

The first method
uses a loop assignment

class Concatenation {
    
    
    public int[] getConcatenation(int[] nums) {
    
    

        int[] ans = new int[nums.length * 2];
        for (int i = 0; i < nums.length; i++) {
    
    
       		//数组复制
            ans[i] = nums[i];
            ans[i + nums.length] = nums[i];
        }
        return ans;
    }
}

The second
way to use the array comes with

class Concatenation2
{
    
    
    public int[] getConcatenation(int[] nums) {
    
    
        int n = nums.length;
        int[] ans = Arrays.copyOf(nums, n*2);
        System.arraycopy(nums, 0, ans, n, n);
        return ans;
}
}

Guess you like

Origin blog.csdn.net/heart_is_broken/article/details/121381563