O(n) time and O(1) space simple java solution


  • 3
    M
    public static void sortColors(int[] A) {
            if(A.length==0||A==null)
            return;
            int pointerOne=0;
            int pointerTwo=A.length-1;
            for(int i=0;i<A.length;i++){
                if(pointerTwo+1==i){
            		break;
            	}
                if(A[i]==0){
                    int temp=A[i];
                    A[i]=A[pointerOne];
                    A[pointerOne]=temp;
                    pointerOne++;
                }else if(A[i]==2){
                    int temp=A[i];
                    A[i]=A[pointerTwo];
                    A[pointerTwo]=temp;
                    pointerTwo--;
                    i--;
                }
            }
        }

Log in to reply
 

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