Leetcode Python超瑣碎筆記: 905-Sort Array By Parity
ofollow,noindex">問題地址 ,難度:Easy
若有錯誤之處請予以指正:)
問題描述
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
題意分析
把偶數奇數分成前後兩部分輸出,空間上in-place當然最好。
我的實現及調優過程
方法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上做手腳。取兩個指標分別指頭尾,取餘後兩個餘數有四種情況,分別處理:
- 前>後
- 前<後
- 前=後=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)