【leetcode】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; } };
标签:Sort,Parity,nums,int,even,evenp,array,odd,leetcode 来源: https://www.cnblogs.com/aalan/p/15579116.html