leetcode 905. Sort Array By Parity

问题来自 leetcode 905. Sort Array By Parity


定义两个指针,一个从index 0往后走,一个从index (size-1)往前走


class Solution {
public:
    vector<int> sortArrayByParity(vector<int>& A) {
        int size = A.size();
        if (size < 2) return A;
        
        int left = 0, right = size -1;
        while(left < right) {
            
            while(left < right && A[left]%2 == 0)
                ++left;
            
            while(left < right && A[right]%2 == 1)
                --right;
            
            if (left < right) {
                int tmp = A[left];
                A[left] = A[right];
                A[right] = tmp;
            }
        }
        
        return A;
    }
};

 

2 comments

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.