[LeetCode] Build Array from Permutation

아르당·2026년 7월 18일

LeetCode

목록 보기
411/563
post-thumbnail

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

Problem

0부터 시작하는 순열 nums가 주어졌을때, nums의 길이와 동일한 배열 ans를 생성해라. 0 <= i < nums.length인 모든 i에 대해 ans[i] = nums[nums[i]]가 성립해야 한다. 생성된 배열 ans를 반환해라.

Example

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

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

Constraints

  • 1 <= nums.length <= 1000
  • 0 <= nums[i] < nums.length
  • nums의 요소는 서로 다르다.

Solved

class Solution {
    public int[] buildArray(int[] nums) {
        int[] ans = new int[nums.length];

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

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

0개의 댓글