python活力練習(xí)Day27
題目描述:
給定一個(gè)非負(fù)整數(shù)數(shù)組 A, A 中一半整數(shù)是奇數(shù),一半整數(shù)是偶數(shù)。
對(duì)數(shù)組進(jìn)行排序,以便當(dāng) A[i] 為奇數(shù)時(shí),i 也是奇數(shù);當(dāng) A[i] 為偶數(shù)時(shí), i 也是偶數(shù)。
你可以返回任何滿足上述條件的數(shù)組作為答案。
示例:
輸入:[4,2,5,7] 輸出:[4,5,2,7] 解釋:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也會(huì)被接受。
提示:
2 <= A.length <= 20000A.length % 2 == 00 <= A[i] <= 1000
解題思路:
第一種:1.首先將A分為兩部分:even列表存儲(chǔ)偶數(shù);odd列表存儲(chǔ)奇數(shù);
2.其次設(shè)置兩個(gè)變量遍歷(i ,j = 0,1 以步長(zhǎng)2進(jìn)行疊加)列表A,將對(duì)應(yīng)位置值用偶數(shù)與奇數(shù)列表值進(jìn)行替代;
3.最終輸出A
第二種:采用雙指針的思想
優(yōu)點(diǎn):未額外創(chuàng)建空間
1.首先創(chuàng)建兩個(gè)指針(i, j = 0,1)表示偶數(shù)和奇數(shù)位置索引
2.其次遍歷列表A,如果對(duì)應(yīng)奇偶位置的值都不一致,那么交換兩個(gè)位置的值,同時(shí)向前 +2;如果偶數(shù)對(duì)應(yīng)位置的值一致而奇數(shù)位置值不一致,那么將偶數(shù)索引(i)向前 + 2;否則 將奇數(shù)索引(j)向前 +2。
3.最終輸出A
python代碼:
1 #方法一:將奇偶數(shù)分開 2 def sortArrayByParityII(A): 3 # 找出列表的所有偶數(shù) 4 even = [i for i in A if i % 2 == 0] 5 # 找出所有的奇數(shù) 6 odd = [i for i in A if i % 2 == 1] 7 8 i, j = 0, 1 # 偶數(shù)奇數(shù) 9 n = len(A) 10 while i < n and j <= n: 11 index = i // 2 12 A[i] = even[index] 13 A[j] = odd[index] 14 i += 2 15 j += 2 16 17 return A 18 19 #方法二:雙指針 20 def sort(A): 21 22 i, j = 0, 1 23 while i < len(A) and j <= len(A): 24 if A[i] % 2 != 0 and A[j] % 2 == 0: 25 A[i], A[j] = A[j], A[i] 26 i += 2 27 j += 2 28 elif A[j] % 2 != 0: 29 j += 2 30 else: 31 i += 2 32 33 return A 34 35 if __name__ == "__main__": 36 A = [4,2,2,5,7,3] 37 print("方法一輸出結(jié)果:{}".format(sortArrayByParityII(A))) 38 print("方法二輸出結(jié)果:{}".format(sort(A)))
輸出結(jié)果:

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/sort-array-by-parity-ii
posted on 2020-06-30 17:07 dangdangA 閱讀(206) 評(píng)論(0) 收藏 舉報(bào)
浙公網(wǎng)安備 33010602011771號(hào)