中興將推出一款航天版新品,向中國航天員送上祝福
阿新 • • 發佈:2021-11-15
Given an array of integersnums, half of the integers innumsareodd, and the other half areeven.Sort the array so that whenevernums[i]is odd,iisodd, and whenevernums[i]is even,iiseven.Returnany 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; } };