解法:双指针
思想:
从两边开始遍历,两边都在不符合的地方停顿,然后两边交换,直到遍历完成。
代码:
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i = 0, j = nums.size() - 1;
while(i < j){
//注意,要时刻判断i < j
while((nums[i] & 1) == 1 && i < j)
i++;
while((nums[j] & 1) == 0 && i < j)
j--;
if(i < j)
swap(nums[i], nums[j]);
}
return nums;
}
};
拓展:
思想:
面试官可能会考察拓展性,本题是奇数前偶数后,题目也可以改成负数和非负数等等。让我们拿出解耦的代码,提高代码的重用性。
遇到不同的题目只需要修改iseven和exchange_oddeven即可,代码重用性更高。
代码:
bool iseven(int n) {
return (n & 1) == 0;
}
//传入函数指针
vector<int> exchange(vector<int>& nums, bool(*func)(int)) {
int i = 0, j = nums.size() - 1;
while (i < j) {
//注意,要时刻判断i < j
//遇到满足的就跳过,即i++和j--
while (i < j && !func(nums[i]))
i++;
while (i < j && func(nums[j]))
j--;
if (i < j)
swap(nums[i], nums[j]);
}
return nums;
}
//用iseven方法处理nums
vector<int> exchange_oddeven(vector<int>& nums) {
return exchange(nums, iseven);
}
出现的问题
我把exchange放在最后时,报错了,调整顺序或者在exchange_oddeven前声明一下exchange就不会报错了。