Loading

【leetocde】922. Sort Array By Parity II

  Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.   Return any answer array that satisfies this condition. 

  slove it in place
  
class Solution {
public:
    vector<int> sortArrayByParityII(vector<int>& nums) {
        //在同一块区域进行遍历查询 双指针 一个只检查奇数位置 一个只检查偶数位置 然后二者进行交换 有点快排的思想
        int n=nums.size();
        int evenp=0,oddp=1;
        while(evenp<n && oddp<n){
            while(evenp<n && nums[evenp]%2==0){
                evenp+=2;
            }
            while(oddp<n && nums[oddp]%2==1){
                oddp+=2;
            }
            if(evenp<n && oddp<n){
                int temp=nums[evenp];
                nums[evenp]=nums[oddp];
                nums[oddp]=temp;
                evenp+=2;
                oddp+=2;
            }
        }
        return nums;

    }
};

 

 
posted @ 2021-11-20 15:02  aalanwyr  阅读(16)  评论(0编辑  收藏  举报