题目分析:[[EVD]] - 剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
简单描述:
- 一个整数数组,使得所有奇数在数组的前半部分,所有偶数在数组的后半部分
限制🚫
- 0 <= nums.length <= 50000
- 0 <= nums[i] <= 10000
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
解题思路:
思路:
- #双指针 分别从nums数组头和尾开始向中间遍历,swap(左边偶数,右边奇数)
- #排序 使用sort()函数+自定义比较函数 #[[C++ STL]]
效率:
- 时间复杂度
- 空间复杂度
代码:
- 双指针
class Solution
{
public:
/*双指针 交换*/
vector<int> exchange(vector<int> &nums)
{
int i = 0, j = nums.size() - 1;
while (i < j)
{
while (i < j && nums[i] % 2 == 1)
i++; //指针i,左边找偶数
while (i < j && nums[j] % 2 == 0)
j--; //指针j,右边找奇数
swap(nums[i], nums[j]);
}
return nums;
}
};
- 排序
class Solution
{
public:
/*排序,奇数在前,偶数在后*/
vector<int> exchange(vector<int> &nums)
{
sort(nums.begin(), nums.end(), [](int a, int b)
{ return a % 2 - b % 2 == 1; });
return nums;
}
};