๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Leetcode

[Leetcode] Create Target Array in the Given Order (#1389)

 

 

๋ฌธ์ œ

 

Given two arrays of integers nums and index. Your task is to create target array under the following rules:

  • Initially target array is empty.
  • From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
  • Repeat the previous step until there are no elements to read in nums and index.

Return the target array.

It is guaranteed that the insertion operations will be valid.

 

 

Example 1:

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

Example 2:

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

Example 3:

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

 

 

ํ•ด์„ค ์ฝ”๋“œ 
class Solution(object):
    def createTargetArray(self, nums, index):
        target = [nums[0]]
        for i in range(1,len(nums)):
            target.insert(index[i],nums[i])    
        return target
๋ถ„์„ > ์ง„์งœ ์‰ฌ์šด ๋ฌธ์ œ์˜€๋Š”๋ฐ ํ˜ผ์ž ์—„์ฒญ ๊ผฌ์•„์„œ ์ƒ๊ฐํ–ˆ๋‹ค. ๊ทธ๋ƒฅ ๊ทธ ์œ„์น˜์— insert ์‹œ์ผœ์ฃผ๋ฉด ๋˜๋Š”๋ฐ, append๋ฅผ ์ผ๋‹จ ํ•˜๊ณ  ์–ด๋–ป๊ฒŒ ์ž๋ฆฌ๋ฅผ ๋ฐ”๊ฟ”์•ผ ํ• ์ง€ ๊ณ ๋ฏผํ•˜๊ณ  ์žˆ์—ˆ๋‹ค. insert๋Š” ๋‹จ์ˆœํžˆ ๋ฐฐ์—ด ์ค‘๊ฐ„์— ์›์†Œ๋ฅผ ์‚ฝ์ž…ํ•˜๋Š” ๊ฒŒ ์•„๋‹ˆ๋ผ, ์• ์ดˆ๋ถ€ํ„ฐ ์œ„์น˜๋ฅผ ์ง€์ •ํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜์ž„์„ ๋ช…์‹ฌํ•˜์ž. 

 

 

 

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

 

'Algorithm > Leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leetcode] Last Moment Before All Ants Fall Out of a Plank (#1503)  (0) 2022.04.21
[Leetcode] Validate Stack Sequences (#946)  (0) 2022.04.21
[Leetcode] Clumsy Factorial (#1006)  (0) 2022.04.21
[Leetcode] Print Words Vertically (#1324)  (0) 2022.04.20
[Leetcode] Reshape the Matrix (#566)  (0) 2022.04.20