[LeetCode] Sort Colors, leetcodecolors
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.
Idea 1: directly traverse the array to count the number of three colors and then fill them in sequence. complexity O (N)
Code 1:
Public void sortColors1 (int [] A) {// count the numbers of 1, 2, and 3 int [] colorCount = new int [3]; for (int I = 0; I <. length; ++ I) {switch (A [I]) {case 0: colorCount [0] ++; break; case 1: colorCount [1] ++; break; case 2: colorCount [2] ++; break;} int from, I = 0, to = 0; while (I <colorCount. length) {from = to; to = to + colorCount [I]; Arrays. fill (A, from, to, I); I ++ ;}}
Train of Thought 2: Simulate the fast-forward, and move 2 and 0 to both sides respectively. This only needs to traverse the array once, and the algorithm complexity O (N)
Code 2:
Public void sortColors (int [] A) {// using the fast sorting idea, final int RED = 0, WHITE = 1, BLUE = 2; int l = 0, r =. length-1, mid = l; while (mid <= r) {if (A [mid] = RED) {int temp = A [mid]; A [mid] = A [l]; A [l] = temp; l ++; mid ++;} else if (A [mid] = BLUE) {int temp = A [mid]; A [mid] = A [r]; A [r] = temp; r -- ;} else {mid ++ ;}}}