剑指Offer21.调整数组顺序使奇数位于偶数前面

这篇博客介绍了两种在Python中交换列表元素的方法。第一种是使用两个辅助列表,分别存储偶数和奇数索引的元素,然后合并得到交换后的列表。第二种方法运用了双指针技巧,从头尾开始遍历,交换不同奇偶性的元素,直至头尾指针相遇。这两种方法都有效地实现了列表元素的原地交换,避免了额外的空间开销。

1.双 list 遍历存储

class Solution:
    def exchange(self, nums: List[int]) -> List[int]:
        tmp1 = []
        tmp2 = []
        for i in nums:
            if i % 2 == 0:
                tmp1.append(i)
            else:
                tmp2.append(i)
        res = tmp2 + tmp1
        return res

2. 首尾双指针

class Solution:
    def exchange(self, nums: List[int]) -> List[int]:
        head, tail = 0, len(nums) - 1
        while head < tail:
            while head < tail and nums[head] % 2 == 1:
                head += 1
            while head < tail and nums[tail] % 2 == 0:
                tail -= 1
            nums[head], nums[tail] = nums[tail], nums[head]
        return nums

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值