Created
March 15, 2020 21:46
-
-
Save shixiaoyu/3d934b5ff175d2164503dcbc77b94523 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void sortColors(int[] A) { | |
if (A == null || A.length == 0) return; | |
int left = 0; | |
int right = A.length - 1; | |
int i = 0; | |
while (i <= right) { // has to be <=, since cur value still needs to be evaluated if swapped back | |
if (A[i] == 1) { | |
i++; | |
} else if (A[i] == 0) { | |
swap(A, i, left); | |
left++; | |
i++; // don't forget this one, we can only exchange 0 or 1 back here, so move forward no matter what | |
} else { // A[i] == 2 | |
swap(A, i, right); | |
right--; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment