Skip to content

Instantly share code, notes, and snippets.

@hsaputra
Created October 4, 2018 07:15
Show Gist options
  • Save hsaputra/b6012f9c862a7e6a015edcd53df46f18 to your computer and use it in GitHub Desktop.
Save hsaputra/b6012f9c862a7e6a015edcd53df46f18 to your computer and use it in GitHub Desktop.
class Solution {
public void sortColors(int[] nums) {
// nums value is 0, 1, 2
int left = 0;
int right = nums.length-1 ;
int i = 0;
// move 0s and 2s so 1s will settle by themselves
while (i < nums.length && i <= right && left < nums.length) {
// If i is 0 then move it to left.
if (nums[i] == 0) {
swap(i, left, nums);
left++;
i++;
} else if (nums[i] == 2) {
swap(i, right, nums);
right--;
} else {
i++;
}
}
}
private void swap(int i, int j, int[] nums) {
//System.out.println("Swap " + i + " with " + j);
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment