題目:Given an array withnobjects 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.
解題思路如下:遍歷數組,存儲每種顏色的個數,再進行排序,示例代碼如下:
/** * @Description: * 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. * @author 徐劍 * @date 2016年3月27日 下午12:32:14 * @version V1.0 */ public class Solution { public static void sortColors(int[] nums) { if(nums==null||nums.length<=0) return; int a[]=new int[3]; for(int i=0;i