알고리즘/배열(array)

Sort Array By Parity python

자코린이 2023. 7. 5. 02:35

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 1:

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.

Example 2:

Input: nums = [0]
Output: [0]

 

Constraints:

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

 

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        """
        1 <= nums.length <= 5000
        0 <= nums[i] <= 5000
        
        Input: nums = [3,1,2,4]
        Output: [2,4,3,1]
        
        짝수 왼쪽, 홀수 오른쪽
        return => list
        """
        if len(nums) == 1: return nums
        
        x = 0
        y = len(nums) - 1
        result = [0 for _ in range(len(nums))]
        
        for i in range(len(nums)):
            if nums[i] % 2 == 0:
                result[x] = nums[i]
                x += 1
            else:
                result[y] = nums[i]
                y -= 1
                
        return result

성능이 딱 중간입니다.

아래 코드는 거의 정답에 가까운 코드입니다.

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        even = []
        odd = []
        for n in nums:
            if n % 2 == 0:
                even.append(n)
            else:
                odd.append(n)
        return even + odd

짝수, 홀수 리스트를 만들어 합치는 방법을 사용하였습니다.