[LeetCode] Create Target Array in the Given Order

아르당·2026년 5월 1일

LeetCode

목록 보기
290/303
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

두 개의 배열 nums와 index가 주어졌을 때, 다음과 같은 규칙에 따라 target 배열을 생성해라.

  • 초기 target 배열은 비어 있다.
  • 왼쪽에서 오른쪽으로 nums[i]와 index[i]를 읽고, target 배열의 index[i]에 nums[i]를 삽입한다.
  • nums와 index에서 읽을 요소가 없을 때까지 이전 과정을 반복해라.

target 배열을 반환해라.

삽입 작업이 유효하게 수행되는 것을 보장한다.

Example

#1
Input: nums = [0, 1, 2, 3, 4], index = [0, 1, 2, 2, 1]
Output: [0, 4, 1, 3, 2]

#2
Input: nums = [1, 2, 3, 4, 0], index = [0, 1, 2, 3, 0]
Output: [0, 1, 2, 3, 4]

#3
Input: nums = [1], index = [0]
Output: [1]

Constraints

  • 1 <= nums.length, index.length <= 100
  • nums.length == index.length
  • 0 <= nums[i] <= 100
  • 0 <= index[i] <= i

Solved

class Solution {
    public int[] createTargetArray(int[] nums, int[] index) {
        List<Integer> target = new ArrayList<>();

        for(int i = 0; i < nums.length; i++){
            target.add(index[i], nums[i]);
        }

        int[] result = new int[nums.length];

        for(int i = 0; i < nums.length; i++){
            result[i] = target.get(i);
        }

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글