๋ฌธ์
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๋ ๋จ์ํ ๋ฐฐ์ด ์ค๊ฐ์ ์์๋ฅผ ์ฝ์ ํ๋ ๊ฒ ์๋๋ผ, ์ ์ด๋ถํฐ ์์น๋ฅผ ์ง์ ํ ์ ์๋ ํจ์์์ ๋ช ์ฌํ์.
'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 |