超琐碎 ≈ 完整记录 + 深入探究 + 任性吐槽
905问题地址,922问题地址,难度:Easy,标签:Array
若有错误之处请予以指正:)
905 问题描述
Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.
Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Note:
1 <= A.length <= 5000
0 <= A[i] <= 5000
922 问题描述
Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
You may return any answer array that satisfies this condition.
Example 1:
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Note:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
题意分析
905是要把偶数奇数分成前后两部分输出,空间上in-place当然最好。922可以视为前者的变体,也是分奇偶两部分,只是放入位置发生了变化。解决了905,再加少许改动就可解决922,下面先列905的实现,最后把其中一种方法改成922(看905的方法时,可以同时想想如何改成922)。
我的实现及调优过程
方法1:92 ms
暴力没什么好说的。
class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
even = []
odd = []
for n in A:
if n % 2 == 0:
even.append(n)
else:
odd.append(n)
return even + odd
- 时间复杂度:O(n)
- 空间复杂度:O(n)
方法2:92 ms
使用列表生成式代替for
循环,并无卵用,估计测试集太小了。
class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
return [x for x in A if x % 2 == 0] + [x for x in A if x % 2 > 0]
- 时间复杂度:O(n)
- 空间复杂度:O(n)
方法3:96 ms
In-place 方法,速度相当。直接在A上做手脚。取两个指针分别指头尾,取余后两个余数有四种情况,分别处理:
- 前=1>后=0
- 前=0<后=1
- 前=后=0
- 前=后=1
class Solution:
def sortArrayByParity(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
i, j = 0, len(A) - 1
while i < j:
i_re = A[i] % 2
j_re = A[j] % 2
# odd - even
if i_re > j_re:
A[i], A[j] = A[j], A[i]
i += 1
j -= 1
# even - odd
elif i_re < j_re:
i += 1
j -= 1
else:
if i_re == 0:
i += 1
else:
j -= 1
return A
- 时间复杂度:O(n)
- 空间复杂度:O(1)
方法3-Golang版:72 ms
刚好这两天在看Golang的基本语法,拿来耍下。快了一丢丢(居然还是个100%),然而我是完全不能理解那些Python下60多ms是怎么刷出来的啊啊啊,卒。
func sortArrayByParity(A []int) []int {
i := 0
j := len(A) - 1
var i_re, j_re int
for ; i<j ;{
i_re = A[i] % 2
j_re = A[j] % 2
if i_re > j_re {
c := A[i] //这里一开始还出了你懂的bug,我已经被Python惯坏
A[i] = A[j]
A[j] = c
i += 1
j -= 1
} else if i_re < j_re {
i += 1
j -= 1
} else {
if i_re == 0 { i += 1} else {
j -= 1}
}
}
return A
}
- 时间复杂度:O(n)
- 空间复杂度:O(1)
方法3-922版:156 ms
相对于方法3
,整体流程不变,需改动指针i
和j
的初始值,while的条件,以及循环内指针的位置调整方法。再一想,如果在方法1
或方法2
上改,那还真不大好改了。同样的,922应该也有一些特别解法只适用于922而难以转为905解法。
class Solution:
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
i, j = 0, 1
while max(i,j) < len(A):
i_re = A[i] % 2
j_re = A[j] % 2
# odd - even
if i_re > j_re:
A[i], A[j] = A[j], A[i]
i += 2
j += 2
# even - odd
elif i_re < j_re:
i += 2
j += 2
else:
if i_re == 0:
i += 2
else:
j += 2
return A
- 时间复杂度:O(n)
- 空间复杂度:O(1)