Sword Finger Offer Interview Question 21. Adjust the array order so that odd numbers are in front of even numbers [Simple]

My solution:

1. Use double pointers, one to traverse before and one to traverse backward, changing the position of even number in front and odd number in back

Words can use the swap function ,,,,

You can use while loop when i and j increase

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int i=0;
        int j=nums.size()-1;
        while(i<j){
            if(nums[i]%2==0 && nums[j]%2==1){
                int tmp=nums[i];
                nums[i]=nums[j];
                nums[j]=tmp;
            }
            if(nums[i]%2==1) i++;
            if(nums[j]%2==0)  j--;
        }
        return nums;
    }
};

2. It is also a double pointer, using the swap function, while loop

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int i=0;
        int j=nums.size()-1;
        while(i<j){
            if(nums[i]%2==0 && nums[j]%2==1)
                swap(nums[i],nums[j]);
            while(i<j&&nums[i]%2==1) i++;
            while(i<j&&nums[j]%2==0)  j--;
        }
        return nums;
    }
};

Published 65 original articles · Like1 · Visits 487

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/105467413