922. 按奇偶排序数组 II
2021-02-15 13:20
标签:数组 mamicode span on() sof += png microsoft lse 922. 按奇偶排序数组 II 标签:数组 mamicode span on() sof += png microsoft lse 原文地址:https://www.cnblogs.com/panweiwei/p/12712663.html思路:
1、遍历A,取出其中的奇数(list1)、偶数(list2);
2、下标为奇数时从list1中取一个元素插入;
3、下标为偶数时从list2中取一个元素插入; 1 class Solution(object):
2 def sortArrayByParityII(self, A):
3 """
4 :type A: List[int]
5 :rtype: List[int]
6 """
7 list1 = []
8 list2 = []
9 for i in range(len(A)):
10 if A[i] % 2 != 0:
11 list1.append(A[i])
12 else:
13 list2.append(A[i])
14 index1 = index2 = 0
15 for i in range(len(A)):
16 if i % 2 != 0:
17 A[i] = list1[index1]
18 index1 += 1
19 else:
20 A[i] = list2[index2]
21 index2 += 1
22 return A
23
24
25 if __name__ == ‘__main__‘:
26 solution = Solution()
27 print(solution.sortArrayByParityII([4, 2, 5, 7]))
上一篇:数据结构与算法(12)—分治策略
下一篇:Java知识点总结