一、题目叙述:
Given an array with n objects colored red, white or blue, sort them 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.
Subscribe to see which companies asked this question.
二、解题思路:
Medium题。
思路1:
(1)直接排序
思路2:
(1)统计每种颜色个数,赋值。
三、源码:
1、
import java.util.Arrays;
public class Solution {
public void sortColors(int[] nums)
{
Arrays.sort(nums);
}
}
2、
import java.util.Arrays;
public class Solution {
public void sortColors(int[] nums)
{
int w = 0;
int r = 0;
int b = 0;
for(int i = 0; i < nums.length; i++)
{
if (nums[i] == 0) w++;
else if (nums[i] == 1) r++;
else b++;
}
for (int i = 0; i < w; i++)
nums[i] = 0;
for (int i = w; i < w + r; i++)
nums[i] = 1;
for (int i = w+r; i < nums.length; i++)
nums[i] = 2;
}
}