面试题21. 调整数组顺序使奇数位于偶数前面

题目:

 

 

解答:

方法一:

 

 

 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 };

 

posted @ 2020-05-09 14:18  梦醒潇湘  阅读(126)  评论(0)    收藏  举报