[Jianzhi 21] Adjust the order of the array so that the odd numbers are in front of the even numbers

Method 1: End-to-end pointer: time O(n), space O(1)

Solution: Exchange the even number at the beginning and the odd number at the end, and then let the pointer one ++ and one--until left >= right

  1. Head pointer: As long as the value of left is odd, it will always be ++
  2. Tail pointer: As long as the value of right is an even number, it will always be--
class Solution {
    
    
public:
    vector<int> exchange(vector<int>& nums) 
    {
    
    
        // 1.双指针
        int left = 0, right = nums.size() - 1;
        while (left < right)
        {
    
    
            if (nums[left] & 1)
            {
    
    
                left++;
                continue;
            }
            if (!(nums[right] & 1))
            {
    
    
                right--;
                continue;
            }
            swap(nums[left++], nums[right--]);
        }
        return nums;
    }
};

Method 2: Fast and slow pointers: time O(n), space O(1)

Solution: As long as the fast pointer touches an odd number, the value of the fast and slow pointer is exchanged, and the slow pointer++

  1. Fast pointer: if it is an even number, then ++, if it is an odd number, exchange and then ++
  2. Slow pointer: every time you exchange ++
class Solution {
    
    
public:
    vector<int> exchange(vector<int>& nums) 
    {
    
    
        // 2.快慢指针
        int slow = 0, fast = 0;
        while (fast < nums.size())
        {
    
    
            if (nums[fast] & 1)
            {
    
    
                swap(nums[slow], nums[fast]);
                slow++;
            }
            fast++;
        }
        return nums;
    }
};

Similar topics

Odd digits are all odd or even digits are even:

  • The biggest pitfall of this question is: the odd number is odd or the even number is even, just make sure that one is established.
  • That is to say, there may be too many odd numbers, and there is no guarantee that the odd numbers are all odd numbers.

Problem solution: double pointer, start from the end of the data, insert the data forward

  1. If the end of the data is odd, insert the position i, and i += 2
  2. If the end of the data is an even number, insert position j, and j += 2
class Solution {
    
    
public:
    /**
     *  奇数位上都是奇数或者偶数位上都是偶数
     *  输入:数组arr,长度大于2
     *  len:arr的长度
     *  将arr调整成奇数位上都是奇数或者偶数位上都是偶数
     */
    void oddInOddEvenInEven(vector<int>& arr, int len) 
    {
    
    
        int i = 0, j = 1;
        while (i < len && j < len)
        {
    
    
            if (arr[len - 1] & 1)    // 奇数,放奇数位
            {
    
    
                swap(arr[len - 1], arr[j]);
                j += 2;
            }
            else 
            {
    
    
                swap(arr[len - 1], arr[i]);
                i += 2;
            }
        }
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/113757657