题目
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.
思路
排序即可,这里的时间复杂度为O(n2),还有另外一种解决方式为设置三个int变量,扫描一遍得出三种颜色的个数,重置一遍数组即可,复杂度为O(n)
代码
public class Solution { public void sortColors(int[] nums) { for(int i = 0 ; i < nums.length - 1 ; ++ i){ int min = i ; for(int j = min + 1 ; j < nums.length ; ++ j){ if(nums[min] > nums[j]){ min = j ; } } int temp = nums[min]; nums[min] = nums[i]; nums[i] = temp; } } }
public class Solution { public void sortColors(int[] nums) { int r = 0; int w = 0; int b = 0; for(int i = 0 ; i < nums.length - 1 ; ++ i){ if(nums[i] == 0) ++r; else if(nums[i] == 1) ++w; else ++b; } int i = 0; for(; i < r ; ++ i){ nums[i] = 0; } for(; i < r + w ; ++ i){ nums[i] = 1; } for(; i < r + w + b ; ++ i){ nums[i] = 2; } } }