当前位置:网站首页>剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
2022-07-20 19:51:00 【愈努力俞幸运】
暴力或双指针
考虑定义双指针 i , j 分列数组左右两端,循环执行:
指针 ii从左向右寻找偶数;
指针 j 从右向左寻找奇数;
将 偶数 nums[i]和 奇数 nums[j]交换。
可始终保证: 指针 ii左边都是奇数,指针 j右边都是偶数 。
记录链表复制容易犯的错误。
'''
#错误原因需要好好理解
class Solution:
def exchange(self, nums):
ans=[]
tmp=nums
#https://blog.csdn.net/qq_37891604/article/details/124528827
#https://blog.csdn.net/weixin_45492560/article/details/120613978
for i in range(len(nums)):
if nums[i]%2:
print(i)
ans.append(nums[i])
tmp.pop(i)
#这里对tmp修改,nums也会改变
#因为是可变对象,指向同一个引用
ans.extend(tmp)
return ans
'''
'''
class Solution:
def exchange(self, nums):
ans=[]
for i in nums:
if i%2:
ans.append(i)
for i in nums:
if i%2==0:
ans.append(i)
return ans
'''
class Solution:
def exchange(self, nums):
i,j=0,len(nums)-1
while i<j:
while i<j and nums[i]%2:i+=1
while i<j and nums[j]%2==0:j-=1
nums[i],nums[j]=nums[j],nums[i]
return nums
a=Solution()
nums = [1,2,3,4]
print(a.exchange(nums))
边栏推荐
- Hilditch 细化(实现一)
- Commercial supply chain management system of big health industry: standardize procurement management and improve enterprise procurement efficiency
- 响应式织梦模板家禽饲养类网站
- Can we have both good quality and low price?
- 小镇做题家的DBA之路
- 【LeetCode】每一轮都要把输入数组看一遍的二分
- VS2005 uses PDB plus source code to locate the code line where the crash occurs
- July 2022 Russian database ranking: Clickhouse ranked first and gigabase ranked second
- Win11 22H2怎么卸载更新补丁?Win11 22H2卸载更新补丁的步骤
- SVG转换为PDF的简单方法
猜你喜欢
随机推荐
(22) blender source code analysis: mouse down message to window call process
Interface test
读书会 | 拨开心理咨询的迷雾:普通人应该如何看待心理咨询
DC-3-靶场实践
truncate 与 delete 有何不同
搭建简易动态ip代理池
A link is automatically added to the picture in the content of dedecms dream weaving article. Click the new window to open the picture
PostgreSQL运维—分布式Citus单机多实例部署
科研 | 研究成果该如何署名?
和客户沟通的总结
oh my god
rce(无回显)
Map and set knowledge points
Hisilicon AI chip (hi35xx): image JPG to BGR upgrade
STL 笔记(十):容器适配器——队列和堆栈
STL notes (XIV): function object
测评 | 你是社恐吗?
STL notes (XI): container adapter - priority queue
Advanced MySQL IV. storage structure of index
快手海外产品 SnackVideo 与 PUBG MOBILE 独家合作 助力手游海外破圈