简单题,说白了就是把偶数往前丢,然后剩下的奇数往后放就好,直接看代码
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
if (nums[right] % 2 == 0) {
swap(nums[left++], nums[right]);
} else {
right--;
}
}
return nums;
}
};
var sortArrayByParity = function(nums) {
let left = 0, right = nums.length-1;
while(left < right) {
if(nums[right] % 2 === 0) {
[nums[left], nums[right]] = [nums[right], nums[left]];
left++;
} else {
right--;
}
}
return nums;
};