Why this version of cpp code doesn't work?


  • 0
    X

    I first wrote this:

    `void sortColors(int A[], int n) {
    	if (n <= 1) return;
    	int redEnd = 0, blueStart = n - 1, cur = 0;
    	while (cur <= blueStart){
    		if (A[cur] == 0) 
    			swap(A[redEnd++], A[cur++]);
    		if (A[cur] == 1) 
    			cur++;
    		if (A[cur] == 2) 
    			swap(A[blueStart--], A[cur]);
    	}
    }`
    

    it cannot pass {2, 0} case and I added else in the code as

    void sortColors(int A[], int n) {
        if(n <= 1) return;
        int redEnd = 0, blueStart = n-1, cur = 0;
        while(cur <= blueStart){
            if(A[cur] == 0) swap(A[redEnd++], A[cur++]);
            else if(A[cur] == 1) cur++;
            else if(A[cur] == 2) swap(A[blueStart--], A[cur]);
        }
    }
    

    and it works. Why the else if is necessary here?


Log in to reply
 

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