LeetCode 陣列排序問題
阿新 • • 發佈:2018-11-17
給定一個非負整數陣列 A, A 中一半整數是奇數,一半整數是偶數。
對陣列進行排序,以便當 A[i] 為奇數時,i 也是奇數;當 A[i] 為偶數時, i 也是偶數。
你可以返回任何滿足上述條件的陣列作為答案
輸入:[4,2,5,7]
輸出:[4,5,2,7]
解釋:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也會被接受。
長的程式碼是我自己寫的:
class Solution: def sortArrayByParityII(self, A): """ :type A: List[int] :rtype: List[int] """ odd = [] even= [] B = [] for i in A: if i % 2 == 1: odd.append(i) else: even.append(i) for x,y in zip(odd,even): B.append(y) B.append(x) return B
短的是看別人寫的(3種方法):
class Solution: def sortArrayByParityII(self, A): even, odd = [a for a in A if not a % 2], [a for a in A if a % 2] return [even.pop() if not i % 2 else odd.pop() for i in range(len(A))] class Solution(object): def sortArrayByParityII(self, A): """ :type A: List[int] :rtype: List[int] """ A.sort(key = lambda x : -(x % 2)) # sort odds in the front for i in range(0,len(A)/2,2): # pick even indexes to the middle of the list & swap values from front and back f = A[i] A[i], A[-(i+1)] = A[-(i+1)], f return A class Solution: def sortArrayByParityII(self, A): j = 0 for i in range(len(A)): if A[i] % 2 == 0 and i % 2 != 0: while A[j] % 2 == 0: j += 2 A[i], A[j] = A[j], A[i] return A