코딩 테스트/99클럽
[99클럽] 코테 스터디 25일차 TIL - 배열(1470. Shuffle the Array)
토자맨
2024. 6. 14. 17:00
문제
문제 설명
num[]에 2n개의 원소가 x1
xn, y1
yn 형태로 존재한다.
x1, y1 ~ 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]
제약 조건
- 1 <= n <= 500
- nums.length == 2n
- 1 <= nums[i] <= 10^3
풀이 방법
풀이 로직
- nums[] = {x1, x2, x3, ..., xn, y1, y2, y3, ..., yn} 형태로 이루어져 있다.
- y 원소의 시작 index는 nums.length/2이다.
- x와 y를 번갈아가며 result[]에 넣는다.
result.add(nums[i]), result.add(nums[i+mid])
코드
class Solution {
public int[] shuffle(int[] nums, int n) {
int mid = nums.length/2;
int[] result = new int[nums.length];
int i = 0;
int j = 0;
while (i < mid) {
result[j] = nums[i]; // x1, x2, ..., xn
result[j+1] = nums[i+mid]; // y1, y2, ..., yn
i++;
j+=2;
}
return result;
}
}
오늘 회고
배열 문제라 그런지 매우 쉬웠다.
뭐 더 할 말이 없다.
고생했다 오늘도!!