Given an array with n objects colored red, white or blue, sort them so, objects of the same color is adjacent, with T He colors in the order red, white and blue.
Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You is not a suppose to use the library's sort function for this problem.
Train of thought 1: Directly traverse the array to count the number of three colors and then fill in order, Complexity O (N)
Code Listing 1:
public void SortColors1 (int[] A) {//Count of the number of a-n-a-th int [] Colorcount = new Int[3]; for (int i =0; i < A.length, ++i) { switch (A[i]) {case 0:colorcount[0] + +; 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 + +; } }
Idea 2: Simulate a fast row, moving 2 and 0 respectively to both sides, this only needs to traverse the array once, the algorithm complexity O (N)
Code Listing 2:
public void Sortcolors (int[] A) {//With the idea of a quick sort, final int RED = 0, white = 1, BLUE = 2; int L =0, r = A.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 + +;}} }
[Leetcode] Sort Colors