Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created March 15, 2020 21:46
Show Gist options
  • Save shixiaoyu/3d934b5ff175d2164503dcbc77b94523 to your computer and use it in GitHub Desktop.
Save shixiaoyu/3d934b5ff175d2164503dcbc77b94523 to your computer and use it in GitHub Desktop.
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