Leetcode No.905

    xiaoxiao2025-06-12  23

    Leetcode No.905 按奇偶排序数组

    ProblemSolvingCode (python3)

    Problem

    给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。

    你可以返回满足此条件的任何数组作为答案。

    示例:

    输入:[3,1,2,4] 输出:[2,4,3,1] 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sort-array-by-parity 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    Solving

    遍歷一次取出偶數,在遍歷一次取出奇數python lambda 用法 先取偶數list,再取奇數list,最後相加

    Code (python3)

    class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: A.sort() result = [] for value in A: if value % 2 ==0: result.append(value) for value in A: if value % 2 ==1: result.append(value) return result class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: # more pythonic result = list(filter(lambda x: x % 2 == 0, A)) + list(filter(lambda x: x % 2 != 0, A)) return result
    最新回复(0)