최대 1 분 소요

Question

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
Return any array that satisfies this condition.

주어진 리스트에서 짝수를 앞쪽으로, 홀수를 뒤로 이동시키는 문제이다.

Example

Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Input: nums = [0]
Output: [0]

Constraints

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000

Solution

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        
        even=[] # 짝수
        odd=[] # 홀수
        
        for x in nums:
            if x%2==0: # 짝수
                even.append(x)
            else:
                odd.append(x)
      
        return even+odd
  • 직접 푼 풀이이다.
  • 주어진 nums 리스트를 순회하며 짝수와 홀수를 나눈다.
  • 짝수 리스트 뒤에 홀수 리스트를 이어 붙여서 리턴한다.


💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기