Easy solution in c++


  • 0
    K

    first iterate the array and count number of red (0) and white (1), then iterate again to assign value 0,1,2 according to the number of red white and blue.

    class Solution {
    public:
        void sortColors(int A[], int n) {
            int red=0;
            int white=0;
            for (int i=0; i<n; ++i) {
                if (A[i]==0) ++red;
                if (A[i]==1) ++white;
            }
            for (int i=0; i<n; ++i) {
                if(i<red) A[i]=0;
                else if(i>=red && i<red+white) A[i]=1;
                else A[i]=2;
            }
        }
    };

Log in to reply
 

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