zoukankan      html  css  js  c++  java
  • leetcode-905 按奇偶数排序

    leetcode-905 按奇偶排序数组

    题目描述:

    给定一个非负整数数组 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)
    
  • 相关阅读:
    流程控制之while循环
    流程控制之if...else
    基本运算符
    基本数据类型
    注释
    用户交互
    常量
    test
    查询方法
    删除代码
  • 原文地址:https://www.cnblogs.com/curtisxiao/p/11241761.html
Copyright © 2011-2022 走看看