-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path905-按奇偶排序数组.py
61 lines (47 loc) · 1.34 KB
/
905-按奇偶排序数组.py
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# -*- encoding: utf-8 -*-
"""
@File : 905-按奇偶排序数组.py
@Time : 2024/05/10 22:45:42
@Author : TYUT ltf
@Version : v1.0
@Contact : [email protected]
@License : (C)Copyright 2020-2030, GNU General Public License
"""
# here put the import lib
from typing import List
"""
给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。
返回满足此条件的 任一数组 作为答案。
示例 1:
输入:nums = [3,1,2,4]
输出:[2,4,3,1]
解释:[4,2,3,1]、[2,4,1,3] 和 [4,2,1,3] 也会被视作正确答案。
示例 2:
输入:nums = [0]
输出:[0]
提示:
1 <= nums.length <= 5000
0 <= nums[i] <= 5000
"""
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
res = []
for num in nums:
if num % 2 == 0:
res.insert(0, num)
else:
res.append(num)
return res
# 双指针法
# l = len(nums)
# i, j = 0, l-1
# while i < j:
# while nums[i] % 2 == 0 and i < j:
# i += 1
# while nums[j] % 2 == 1 and i < j:
# j -= 1
# nums[i], nums[j] = nums[j], nums[i]
# return nums
obj = Solution()
nums = [2, 2, 2, 1, 4, 5]
print(obj.sortArrayByParity(nums))