首页 分享 Python Leetcode(905.按奇偶排序数组)

Python Leetcode(905.按奇偶排序数组)

来源:萌宠菠菠乐园 时间:2024-09-18 02:42

Python Leetcode(905.按奇偶排序数组)

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

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

示例:

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

提示:

1 <= A.length <= 5000 0 <= A[i] <= 5000 12

Solution:(最开始的思路是遍历数组,对元素进行判断,奇数的话添加在结果列表后面,偶数的话插入在结果列表前面。)

class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ result = [] for each in A: if each % 2 == 0: result.insert(0, each) else: result.append(each) return result 123456789101112131415

solution = Solution() print(solution.sortArrayByParity([1, 3, 5, 4, 6, 7])) 12

[6, 4, 1, 3, 5, 7] 1

Solution:(看了题解之后,发现这道题可以理解成按奇偶性排序,利用双指针,前指针遇到奇数停下,后指针遇到偶数停下,然后交换。)

class Solution(object): def sortArrayByParity(self, A): """ :type A: List[int] :rtype: List[int] """ start, end = 0, len(A)-1 while start < end: if A[start] % 2 == 0: start += 1 elif A[end] % 2 == 1: end -= 1 else: A[start], A[end] = A[end], A[start] return A

12345678910111213141516

solution = Solution() print(solution.sortArrayByParity([1, 3, 5, 4, 6, 7])) 12

[6, 4, 5, 3, 1, 7] 1

相关知识

leetcode
找出数组a[]中符合a[i]+a[j]=K的数对
狗狗智商按学历排序,你家狗狗什么学历
使用字节数组创建String后通过getBytes()得到的数组与创建时不同
Python学习笔记 2020.10.1
np.unique(ar, return
11.1.1 JavaScript基本语法
Python笔试题
task1
运用C语言设计一个电子宠物程序,实现下列基本功能。

网址: Python Leetcode(905.按奇偶排序数组) https://www.mcbbbk.com/newsview182113.html

所属分类:萌宠日常
上一篇: 区块链宠物系统开发定...
下一篇: 【宠物用猫包】

推荐分享