leetcode-905 按奇偶数排序

匿名 (未验证) 提交于 2019-12-02 23:52:01

题目描述:

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

解法一:头尾指针,向中间走

class Solution:     def sortArrayByParity(self, A: List[int]) -> List[int]:         if not A:             return         i,j = 0,len(A)-1         while i<=j:             while i<len(A) and A[i]%2 == 0 :                 i += 1             while j>=0 and A[j]%2 == 1 :                 j -= 1             if i>=len(A) or j<0 or i>j:                 break             A[i],A[j] = A[j], A[i]             i += 1             j -= 1         return A

解法二:

class Solution:     def sortArrayByParity(self, A: List[int]) -> List[int]:         return sorted(A, key = lambda x : x % 2)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!