leetcode 922. Sort Array By Parity II(python)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了leetcode 922. Sort Array By Parity II(python),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1700字,纯文字阅读大概需要3分钟。
内容图文
描述
Given an array A of non-negative integers, half of the integers in A are odd, and half of the integers are even.
Sort the array so that whenever A[i] is odd, i is odd; and whenever A[i] is even, i is even.
You may return any answer array that satisfies this condition.
Example 1:
Input: [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Note:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
解析
这里的题意比较简单,就是给出的 A 中有各有相等数量的奇数和偶数,然后按照 A[i] 是偶数, i 是偶数, A[i] 是奇数, i 是奇数的方式排列。结果只要满足规则即可。利用 list 的一些特殊使用技巧即可完成,时间复杂度是 O(N), 空间复杂度是 O(N),N 是 A 的长度。
解答
class Solution(object):
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
N = len(A)
result = [None]*N
result[::2] = [x for x in A if x%2==0]
result[1::2] = [x for x in A if x%2==1]
return result
运行结果
Runtime: 192 ms, faster than 77.50% of Python online submissions for Sort Array By Parity II.
Memory Usage: 14 MB, less than 32.79% of Python online submissions for Sort Array By Parity II.
解析
另外一种思路是利用 i 指针来找偶数,j 指针来找奇数。 让 A[i] 成为偶数,否则通过 j 来继续遍历数组来找到合适的数字进行交换。时间复杂度为 O(N),空间复杂度为 O(1),N 是 A 的长度。
解答
class Solution(object):
def sortArrayByParityII(self, A):
"""
:type A: List[int]
:rtype: List[int]
"""
j = 1
for i in range(0, len(A), 2):
if A[i]%2:
while A[j]%2:
j+=2
A[i],A[j] = A[j],A[i]
return A
运行结果
Runtime: 200 ms, faster than 53.23% of Python online submissions for Sort Array By Parity II.
Memory Usage: 13.8 MB, less than 76.98% of Python online submissions for Sort Array By Parity II.
内容总结
以上是互联网集市为您收集整理的leetcode 922. Sort Array By Parity II(python)全部内容,希望文章能够帮你解决leetcode 922. Sort Array By Parity II(python)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。