-
[LeetCode] 1470. Shuffle the ArrayAlgorithm/LeetCode 2021. 9. 24. 09:05
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7] Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1]
Example 3:
Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2]
Constraints:
- 1 <= n <= 500
- nums.length == 2n
- 1 <= nums[i] <= 10^3
class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: stack = [] for i in range(n): stack.append(i) stack.append(i+n) stack02 = [] for j in stack: stack02.append(nums[j]) return stack02
# idea
index 번호가 바뀌는 패턴을 이용하였다.
n =3 일 때, 123456 => 142536
i 뒤에는 i +n 이 오게된다.
# other way def shuffle(self, nums: List[int], n: int) -> List[int]: res = [] for i, j in zip(nums[:n],nums[n:]): res += [i,j] return res
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] 442. Find All Duplicates in an Array (0) 2021.09.25 [LeetCode] 1460. Make Two Arrays Equal by Reversing Sub-arrays (0) 2021.09.25 [Leetcode] 1742. Maximum Number of Balls in a Box (0) 2021.09.23 [Leetcode] 1748. Sum of Unique Elements (0) 2021.08.22 [Leetcode] 961. N-Repeated Element in Size 2N Array (0) 2021.08.22