905. 按奇偶排序数组
给你一个整数数组 nums,将 nums 中的的所有偶数元素移动到数组的前面,后跟所有奇数元素。
返回满足此条件的 任一数组 作为答案。
示例 1:
输入:nums = [3,1,2,4]
输出:[2,4,3,1]
解释:[4,2,3,1]、[2,4,1,3] 和 [4,2,1,3] 也会被视作正确答案。
示例 2:
输入:nums = [0]
输出:[0]
提示:
1 <= nums.length <= 5000
0 <= nums[i] <= 5000
我觉得我写起来思路很直接
应该有优化的方法 例如双指针之类的
不过我还是偷懒了
直接把偶数放在新数组前 奇数放在新数组后就过了
class Solution { public: vector<int> sortArrayByParity(vector<int>& nums) { vector<int> ans; for(int i = 0; i< nums.size(); i++) { if(nums[i] % 2 == 0) { ans.emplace(ans.begin(), nums[i]); } else { ans.emplace_back(nums[i]); } } return ans; } };