BiruLyu
7/28/2017 - 6:30 PM

## 75. Sort Colors(#).java

``````public class Solution {
public void sortColors(int[] nums) {
int i = 0;
int left = 0;
int right = nums.length - 1;

while (i <= right) {
if (nums[i] == 0) {
swap(nums, i++, left++);
} else if (nums[i] == 2) {
swap(nums, i, right--);
} else {
i++;
}
}
}
private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}``````
``````   public void sortColors(int[] nums) {
int start = 0;
int end = nums.length - 1;
int[] arr = new int[nums.length];
for(int i = 0; i < nums.length; i++)
{
if(nums[i] == 0)
{
arr[start] = 0;
start++;
}
else if(nums[i] == 2)
{
arr[end] = 2;
end--;
}
}
for(int i = start; i <= end; i++)
{
arr[i] = 1;
}
for(int i = 0; i < nums.length; i++)
{
nums[i] = arr[i];
}
}
}``````
``````public class Solution {
public void sortColors(int[] nums) {

int r = 0;
int w = 0;
int b = 0;
for (int num : nums) {
if (num == 0) {
nums[b++] = 2;
nums[w++] = 1;
nums[r++] = 0;

} else if (num == 1) {
nums[b++] = 2;
nums[w++] = 1;
} else if (num == 2) {
b++;
}
}
}
}``````