What's wrong with my code? I test in VC and it works, but OJ give "Time Limit Error"


  • 0
    F
    void sortColors(int A[], int n) {
        int p0=0,p1=0,p2=n-1;
        while(p1<p2 && p0<p2){
            if(A[p1]==0 && A[p0]==1){
                swap(A[p1],A[p0]);
            }
            if(A[p1]==2 && A[p2]!=2){
                swap(A[p1],A[p2]);
            }
            if(A[p2]==2){
                p2--;
            }
            if(A[p1]==1){
                p1++;
            }
            if(A[p0]==0){
                p0++;
            }
        }
    }
    void swap(int a, int b){
        int temp=a;
        a=b;
        b=temp;
    }

  • 0
    M

    Are you certain it works? I think I see what you are aiming for, but does the swap method actually do anything? From what I remember, ints are passed by value, so swapping a and b in the method doesn't actually change anything in A.


  • 0
    F

    Yes you are right


Log in to reply
 

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