코딩 알고리즘 문제/Leetcode

905. Sort Array By Parity (Array, Two Pointers, Sorting)

highlightmoon 2025. 10. 28. 08:26
반응형

링크 - https://leetcode.com/problems/sort-array-by-parity/description/

난이도 - Easy

Intuition

이 문제는 쉬우므로 in-place변경을 통해 Space complexity가 O(1)로 할 수 있는 방법으로 문제를 풀어보겠다.

1. 먼저 left, right를 0, len(nums) - 1로 초기화한다.

2. left<right일때 while문을 돌린다. 

3. 먼저 nums[left]가 홀수이고 nums[right]가 짝수이면, 둘을 swap한다.

4. 아니면 둘 다 홀수이거나 둘 다 짝수, 혹은 nums[left]가 짝수이고 nums[right]가 홀수이다. 이때 nums[left]가 짝수이면 left += 1하고, nums[right]가 홀수이면 right -= 1한다.

Code

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        left, right = 0, len(nums) - 1
        while left < right:
            if nums[left] % 2 > nums[right] % 2:
                nums[left], nums[right] = nums[right], nums[left]
            if nums[left] % 2 == 0:
                left += 1
            if nums[right] % 2 == 1:
                right -= 1
        return nums

Complexity

Time Complexity: O(N) one pass from both end

Space Complexity: O(1) in-place operation

반응형