标签:ref pre 不同 code 快慢指针 swap href offer change
题目链接:https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i = 0;
int j = nums.size() - 1;
while(i < j)
{
if(nums[j] % 2 == 0)
j--;
else if(nums[i] % 2 == 1)
i++;
else
swap(nums[i], nums[j]);
}
return nums;
}
};
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i = 0;
int j = nums.size() - 1;
while(i < j)
{
if((nums[j] & 1) != 1)
j--;
else if((nums[i] & 1) != 0)
i++;
else
swap(nums[i], nums[j]);
}
return nums;
}
};
与上面指针的初始指向不同,刚开始i=j=0;
j为快指针,i为慢指针
i用来记录下一个要交换偶数的位置
j用来奇数
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i = 0, j = 0;
while (j < nums.size())
{
if (nums[j] & 1) //找奇数
{
swap(nums[i], nums[j]);
i ++;
}
j ++;
}
return nums;
}
};
【剑指offer】【双指针】21.调整数组顺序使奇数位于偶数前面
标签:ref pre 不同 code 快慢指针 swap href offer change
原文地址:https://www.cnblogs.com/Trevo/p/12731337.html