0%

[筆記] Leetcode - 905. Sort Array By Parity

https://leetcode.com/problems/contains-duplicate/

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
left, right = 0, len(nums) - 1

while left < right:
if nums[right] % 2 == 0 and nums[left] % 2 == 1:
nums[right], nums[left] = nums[left], nums[right]
left += 1
right -= 1

if nums[left] % 2 == 0:
left += 1

if nums[right] % 2 == 1:
right -= 1
return nums
1
2
3
4
5
6
7
8
9
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]: even_idx = 0

for i in range(len(nums)):
if nums[i] % 2 == 0:
nums[even_idx], nums[i] = nums[i], nums[even_idx]
even_idx += 1

return nums