easy 剑指 Offer 调整数组顺序使奇数位于偶数前面 头尾双指针 快慢双指针

在这里插入图片描述


头尾双指针:

c++


class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int l=0;
        int r= nums.size()-1;
        while(l<r){
            if(nums[l]%2 != 0){      // 前奇数,满足条件
                l++;                 // 跳过,进入下次循环
                continue;
            }
            if(nums[r]%2 == 0){      // 后偶,满足条件
                r--;
                continue;
            }
            // 前后都不满足条件,交换
            swap(nums[l], nums[r]);
        }

        return nums;
    }
};

python


class Solution:
    def exchange(self, nums: List[int]) -> List[int]:
        l=0
        r=len(nums)-1
        while l<r:
            if nums[l]%2 != 0:  # 前奇,不处理,指针后移
                l += 1
                continue
            if nums[r]%2 == 0:   # 后偶,不处理,指针前移
                r -= 1
                continue

            # 前后都不满足条件,处理
            nums[l], nums[r] = nums[r], nums[l]

        return nums

在这里插入图片描述


快慢双指针:


class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int l=0;
        int f=0;
        int n = nums.size();
        while(f<n){
            if(nums[f]%2 != 0){   // 快指针遇到偶数,慢指针不动,等待快指针遇到奇数,交换
                swap(nums[l], nums[f]);
                l++;
            }
            f++;
        }
        return nums;
    }
};

python


class Solution:
    def exchange(self, nums: List[int]) -> List[int]:
        l = 0
        f = 0
        n = len(nums)
        while f<n:
            if nums[f]%2 != 0:
                nums[f],nums[l] = nums[l],nums[f]
                l += 1
            f += 1

        return nums

在这里插入图片描述


辅助容器:

c++


class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        vector<int> res;
        for(auto n:nums){
            if(n%2!=0){
                res.insert(res.begin(), n);  // 在指定位置插值 insert (位置迭代器)
            }else{
                res.push_back(n);
            }
        }
        return res;
    }
};

python


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值