[LeetCode] Sort Array By Parity II

준규·2023년 4월 3일

1.문제


Given an array of integers nums, half of the integers in nums are odd, and the other half are even.

Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

Return any answer array that satisfies this condition.


정수 배열 nums가 주어질 때 절반은 짝수 , 절반은 홀수라고 한다. 이 때 홀수 인덱스에는 홀수 , 짝수 인덱스에는 짝수가 위차하도록 nums를 정렬해서 리턴하는 문제이다.


Example 1

Input: nums = [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Example 2

Input: nums = [2,3]
Output: [2,3]

Constraints:

  • 2 <= nums.length <= 2 * 10^4
  • nums.length is even.
  • Half of the integers in nums are even.
  • 0 <= nums[i] <= 1000

2.풀이

  1. 배열을 순회하면서 짝수이면 even 배열에 따로 저장하고 nums에서 빼준다.
  2. result 배열에 짝수 , 홀수 순서대로 넣어준다.

/**
 * @param {number[]} nums
 * @return {number[]}
 */
const sortArrayByParityII = function (nums) {
  const result = [];
  const even = [];

  // 배열을 순회하면서 짝수를 even 배열에 저장하고 nums에서 빼준다
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] % 2 === 0) {
      even.push(nums[i]);
      nums.splice(i, 1);
      i--;
    }
  }

  // result 배열에 짝수 , 홀수 를 하나씩 넣어준다
  for (let i = 0; i < nums.length; i++) {
    result.push(even[i]);
    result.push(nums[i]);
  }

  return result;
};

3.결과

profile
안녕하세요 :)

0개의 댓글