题目:
解答:
方法一:
1 class Solution { 2 public: 3 vector<int> exchange(vector<int>& nums) 4 { 5 int left = 0; 6 int right = nums.size() - 1; 7 while (left < right) 8 { 9 if ((nums[left] & 1) != 0) 10 { 11 left ++; 12 continue; 13 } 14 if ((nums[right] & 1) != 1) 15 { 16 right --; 17 continue; 18 } 19 20 swap(nums[left++], nums[right--]); 21 } 22 return nums; 23 } 24 };
方法二:快慢指针法
1 class Solution { 2 public: 3 vector<int> exchange(vector<int>& nums) 4 { 5 int low = 0; 6 int fast = 0; 7 while (fast < nums.size()) 8 { 9 if (nums[fast] & 1) 10 { 11 swap(nums[low], nums[fast]); 12 low ++; 13 } 14 fast ++; 15 } 16 return nums; 17 } 18 };
原文:https://www.cnblogs.com/ocpc/p/12857171.html