905. Sort Array By Parity

개굴·2024년 5월 23일

leetcode

목록 보기
8/51
  • python3

Problem

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

Pseudocode

  1. Set two pointers: one starting from the beginning and the other from the end.
  2. If the element at the start pointer is odd, swap it with the element at the end pointer, then decrease the end pointer.
  3. If the element at the start pointer is even, simply increase the start pointer.

Code

First Solution

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        
        startPointer = 0
        endPointer = len(nums) - 1

        while startPointer < endPointer:
            if nums[startPointer] %2 !=0:
                if  nums[endPointer] %2 == 0:
                      nums[startPointer], nums[endPointer] = nums[endPointer], nums[startPointer]
                endPointer -= 1
            else:
                startPointer += 1
            
        return nums

Improved Solution

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        
        startPointer = 0
        endPointer = len(nums) - 1

        while startPointer < endPointer:
            if nums[startPointer] %2 !=0:
                nums[startPointer], nums[endPointer] = nums[endPointer], nums[startPointer]
                endPointer -= 1
            else:
                startPointer += 1
            
        return nums

Result

  • After removing unnecessary conditions, the runtime has slightly decreased.

  • Time Complexity : O(n) as we are traveling the array only once.
  • Space Complexity : O(1) as we are not using any extra space.

Review

  • I solve the problem on my own agian. What a fantastic improvement!
profile
알쏭달쏭혀요

0개의 댓글