Exact one loop solution in C++


  • 2
    C
    class Solution {
    public:
        void sortColors(int A[], int n) {
            int Zero = 0, Two = n - 1;
            for (int i = 0; i <= Two; ) {
                if (A[i] == 1) {
                    if (A[Two] == 0) swap(A[i], A[Two]);
                    else i++;
                }
                else if (A[i] == 0) {
                    if (i != Zero) swap(A[i], A[Zero++]);
                    else i++;
                }
                else if (A[i] == 2) {
                    if (i != Two) swap(A[i], A[Two--]);
                    else i++;
                }
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.