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
1 public class Solution { 2 public void sortColors(int[] nums) { 3 int i = -1, j = -1, k = -1;//三个指针分别表示数字0、1、2的下标 4 for(int n = 0; n < nums.length; n++){ 5 if(nums[n] == 0){// 元素为0, j、k 都要往后走一位 6 nums[++k] = 2; 7 nums[++j] = 1; 8 nums[++i] = 0; 9 }else if(nums[n] == 1){ 10 nums[++k] = 2; 11 nums[++j] = 1; 12 }else 13 nums[++k] = 2; 14 } 15 } 16 }
该题是荷兰国旗三色问题。
解法二:
可以使用map 记录 0,1,2出现的个数。重新将数组赋值一遍。循环两便。