본문 바로가기
코딩테스트/리트코드LeetCode

[리트코드LeetCode][Easy][JAVA]1929. Concatenation of Array

by 빔o0O 2025. 1. 26.

 

문제

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 1:

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]

Example 2:

Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- 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]

 

Constraints:

  • n == nums.length
  • 1 <= n <= 1000
  • 1 <= nums[i] <= 1000

 

 


 

분석

  1. 길이가 n인 interger 배열 nums가 주어진다. 그리고 ans 라는 배열을 만드는데 이 배열은 아래와 같은 특성을 가진다.
    - 길이는 2n
    - ans[i] == nums[i]
    - 0 <= i < n 일 때, ans[i+n] == nums[i]
  2. 쉽게 말하자면, nums 의 요소가 두 번 반복된 배열을 반환하면 된다는 얘기.

 

 


 

답안

class Solution {
    public int[] getConcatenation(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len * 2];
        for(int i = 0; i < len; i++){
            ans[i] = nums[i];
            ans[i + len] = nums[i];
        }
        return ans;
    }
}

 

 

 


 

다른 사람의 답안

 

// 메모리가 44.7mb 인 코드

class Solution {
    public int[] getConcatenation(int[] nums) {
        int n = nums.length;
        int[] ans = new int[2*n];
        for(int i=0; i<n; i++){
            ans[i] = ans[i+n] = nums[i];
        }
        return ans;
    }
}

 

// 속도가 0ms인 코드

class Solution {
    public int[] getConcatenation(int[] nums) {
        int[] result = new int[2 * nums.length];
        System.arraycopy(nums, 0, result, 0, nums.length);
        System.arraycopy(nums, 0, result, nums.length, nums.length);

        return result;
    }
}

 

 

💡 참고

 

  • System.arraycopy(nums, 0, result, 0, nums.length);
    이 코드는 nums 배열의 0번 인덱스부터 시작하여 nums.length까지의 원소를 result 배열에 복사합니다. 즉, nums 배열의 모든 원소를 result 배열의 앞부분에 복사하는 것입니다.
  • System.arraycopy(nums, 0, result, nums.length, nums.length);
    이 코드는 다시 nums 배열의 0번 인덱스부터 nums.length까지의 원소를 복사하되, 이번에는 result 배열의 nums.length 위치부터 시작해서 복사합니다. 즉, result 배열에서 두 번째 부분을 nums 배열의 원소로 채우는 것입니다.

 

 

 


 

🔗링크