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

vector<int> nums;
...
partition(nums.begin(), nums.end(), [](int x){
    
     return x % 2 == 1 ? });
  • 思路:
    1.首尾双指针:O(n):需要遍历一次数组,O(1)
    保证l之前的都是奇数,r之前的都是偶数,直至二者相遇;
class Solution {
    
    
public:
    vector<int> exchange(vector<int>& nums) {
    
    
        int n = nums.size();
        int l = 0, r = n - 1;
        while (l < r) {
    
    
            while (l < r && (nums[l] & 1) == 1) ++l;//找到左侧第一个奇数
            while (l < r && (nums[r] & 1) == 0) --r;//找到右侧第一个偶数
            if (l < r) swap(nums[l], nums[r]);//能进入这个分支,说明左奇右偶,则交换
        }
        return nums;
    }
};

2.使用库函数partition,这样可以灵活更改划分条件

class Solution {
    
    
public:
    vector<int> exchange(vector<int>& nums) {
    
    
        partition(nums.begin(), nums.end(), [](int x){
    
     return x % 2 == 1; });
        return nums;
    }
};

猜你喜欢

转载自blog.csdn.net/jiuri1005/article/details/113868222