题目来源:
https://leetcode.com/problems/sort-array-by-parity/
自我感觉难度/真实难度:
easy/easy
题意:
把列表里的偶数放在前面,奇数放在后面
分析:
自己的代码:
class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ c=[] b=[] for i in range(len(A)): if A[i]%2==0: b.append(A[i]) else: c.append(A[i]) b.extend(c) return b
代码效率/结果:
Runtime: 108 ms, faster than 17.99% of Python online submissions for Sort Array By Parity.
这里range就是产生一个list[],其实可以直接对【】进行迭代。
优秀代码:
class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ return sorted(A, key = lambda x : x % 2)
代码效率/结果:
Runtime: 96 ms, faster than 31.51% of Python online submissions for Sort Array By Parity.
神奇的使用了sorted函数,方便排序,key是自己选择的排序关键字
自己优化后的代码:
class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ c=[] b=[] for i in A: if i%2==0: b.append(i) else: c.append(i) b.extend(c) return b
Runtime: 88 ms, faster than 46.64% of Python online submissions for Sort Array By Parity.
反思改进策略:
1.学习了如何使用sorted函数,sort是对列表【】使用的
原文地址:https://www.cnblogs.com/captain-dl/p/10227865.html
时间: 2024-10-09 00:38:13