题目描述
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library’s sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
方法思路
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's,
then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?
Approach1: Two-pass
class Solution {
//Runtime: 0 ms, faster than 100.00% of Java
//Memory Usage: 34.8 MB, less than 86.60% of Java
public void sortColors(int[] nums) {
int red = 0, white = 0, blue = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 0)
red++;
else if(nums[i] == 1)
white++;
else
blue++;
}
for(int i = 0; i < red; i++)
nums[i] = 0;
for(int i = red; i < (red + white); i++)
nums[i] = 1;
for(int i = (red + white); i < nums.length; i++)
nums[i] = 2;
}
}
Approach2: One-pass
class Solution{
// one pass in place solution,想到这个方法的人真是个天才
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 37.4 MB, less than 8.64%
public void sortColors(int[] nums) {
int n0 = -1, n1 = -1, n2 = -1;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == 0)
{
nums[++n2] = 2;
nums[++n1] = 1;
nums[++n0] = 0;
}
else if (nums[i] == 1)
{
nums[++n2] = 2;
nums[++n1] = 1;
}
else if (nums[i] == 2)
{
nums[++n2] = 2;
}
}
}
}
Approach3: One-pass by swap
class Solution{
//Runtime: 0 ms, faster than 100.00% of Java
//Memory Usage: 34.9 MB, less than 77.52%
public void sortColors(int[] nums){
int j = 0, k = nums.length - 1;
for(int i = 0; i <= k; i++){
if(nums[i] == 0)
//i是循环迭代的索引
//j是迭代所遇到的最后一个值为1的索引
//k是2的索引
swap(nums, i, j++);
else if(nums[i] == 2)
//若遇到2则通过交换将其放在nums[k]
swap(nums, i--, k--);
//若是遇见1,则将其跳过,并进入下一次迭代
}
}
public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}