https://leetcode.com/problems/create-target-array-in-the-given-order/

 

Create Target Array in the Given Order - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 풀이를 하자면, nums와 index들이 주어지고

해당 index에 값을 넣어서 배열을 만들어 주면 되는 간단한 문제!!

 

근데, 생각보다 쉽게 풀렸다?

 

왜냐면, result를 초기화하게 되면 인덱스 값이 이미 존재한지 몰랐다....!

 

그래서, result를 0으로 nums의 갯수로 초기화하였는데, 그럴 필요가 없었다. 

이 작업을 하면 0을 없애야하는 추가 작업도 해야하고... 배웠다!

 

생각해보니깐, 이 문제에서만 통한다.

 

테스트 케이스를 보니깐,

갑자기 이상 인덱스가 100으로 가지 않는다.

점점 숫자가 커진다. 오름차순 정렬이기 때문에 비어있는 인덱스가 없기 떄문에 괜찮았던 것이다.

 

 

class Solution {
    func createTargetArray(_ nums: [Int], _ index: [Int]) -> [Int] {
        var result: [Int] = []
        //var result = Array(repeating:0,count:nums.count)
        
        for i in 0..<nums.count{
            result.insert(nums[i],at: index[i])
        }
        
        return result
        
    }
}

다른 고수분들의 풀이도 비슷해서 패스!

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode_Build an Array with Stack Operations  (0) 2022.07.01
Leetcode_Available Captures for Rook  (0) 2022.07.01
Leetcode_Water Bottles  (0) 2022.07.01
Leetcode_Distribute Candies to People  (0) 2022.06.30
Leetcode_Transpose Matrix  (0) 2022.06.30

+ Recent posts