-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path27_sort_array_by_parity.py
More file actions
39 lines (28 loc) · 970 Bytes
/
27_sort_array_by_parity.py
File metadata and controls
39 lines (28 loc) · 970 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution:
def sortArrayByParity_brute_force(self, nums: list[int]) -> list[int]:
res = []
for i in range(len(nums)):
if nums[i] % 2 == 0:
res.append(nums[i])
for i in range(len(nums)):
if nums[i] % 2 != 0:
res.append(nums[i])
return res
def sortArrayByParity(self, nums: list[int]) -> list[int]:
left, right = 0, len(nums) - 1
while left < right:
if nums[left] % 2 == 0:
left += 1
elif nums[right] % 2 != 0:
right -= 1
else:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
return nums
if __name__ == "__main__":
obj = Solution()
nums1 = [3,1,2,4]
print(obj.sortArrayByParity(nums1))
nums2 = [0]
print(obj.sortArrayByParity(nums2))