Thursday, December 11, 2014

Sort Colors LeetCode

Two passes are easy to understand. Count and put all the numbers in.

public void sortColors(int[] A) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (A == null || A.length == 0) return;
         int[] helper = new int[3];
         for (int i=0; i<A.length; i++) {
             helper[A[i]] ++;
         }
       
         int index = 0;
         for (int j=0; j<3; j++) {
             while (helper[j]-- > 0) {
                 A[index++] = j;
             }
         }
    }

OK. Let's make it better.
ONE Pass.
index0 and index1 are two pointer for the current location of 0 and 1.

public void sortColors(int[] A) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
       if (A==null||A.length==0) return;
       int ind0 = 0;
       int ind1 = 0;
       for (int i=0; i<A.length; i++) {
           if (A[i] == 0) {
               A[i] = 2;
               A[ind1++] = 1;
               A[ind0++] = 0;
           } else if (A[i] == 1) {
               A[i] = 2;
               A[ind1++] = 1;
           }
       }
    }

No comments:

Post a Comment