[LeetCode] Shuffle the Array

아르당·2026년 5월 13일

LeetCode

목록 보기
307/561
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

[x1,x2,...,xn,y1,y2,...,yn] 형태의 2n개 요소로 구성된 배열 nums가 주어진다.
[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: x1 = 2, x2 = 5, x3 = 1, y1 = 3, y2 = 4, y3 = 7일 때, 답은 [2, 3, 5, 4, 1, 7]이다.

#2
Input: nums = [1, 2, 3, 4, 4, 3, 2, 1], n = 4
Output: [1, 4, 2, 3, 3, 2, 4, 1]

#3
Input: nums = [1, 1, 2, 2], n = 2
Output: [1, 2, 1, 2]

Constraints

  • 1 <= n <= 500
  • nums.length == 2n
  • 1 <= nums <= 10^3

Solved

class Solution {
    public int[] shuffle(int[] nums, int n) {
        int[] result = new int[nums.length];

        for(int i = 0; i < nums.length; i++){
            if(i % 2 == 0){
                result[i] = nums[i / 2];
            }else{
                result[i] = nums[n + (i / 2)];
            }
        }

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글