剑指 Offer 21 调整数组顺序使奇数位于偶数前面

标签: 剑指 Offer 发布于:2022-02-23 14:21:54 编辑于:2022-02-23 14:34:53 浏览量:395

概述

https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/

前后指针

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int l = 0;
        int r = nums.size() - 1;
        while (l < r) {
            while (l < r && nums[l] % 2 == 1) l ++;
            while (l < r && nums[r] % 2 == 0) r --;
            if (l < r) {
                int t = nums[l];
                nums[l] = nums[r];
                nums[r] = t;
                l ++;
                r --;
            }
        }
        return nums;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/