Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/71/
Topics
Given an array of n objects (including k different colors, numbered 1 to K), the objects are categorized so that objects of the same color are adjacent and sorted in the order of 1,2,...K.
Online test
http://www.lintcode.com/zh-cn/problem/sort-colors-ii/
Answer
There are two methods of this problem.
method One: You can use an O (k) array bucket, and then sweep the original array, statistics of how many of each color is stored in the array bucket inside, and then the title request color sorting, in fact, the B inside the statistics re-output to the original array is good.
method Two: the topic requires not to use an extra array, you can use the idea above, just to use the original array A to count the frequency of each color. Since the original color is definitely a positive 1-k, so we can use a negative number such as a[i]=-k, indicating that the first color in the original array in the presence of K-times. The original array is also reused as a bucket array, so what should we do? First for the loop to iterate over the original array, if sweep to A[i], first check a[a[i]] is a positive, if it is a[a[i]] move A[i] storage, and then the A[a[i]] to 1 (indicating that the position is a counter, 1). If A[a[i]] is a negative number, then the place has been counted, then the a[a[i]] count minus one, and the color[i] set to 0 (indicating that it has been computed here), and then iterate down the next count, so that after iterating through all the elements of the original array, Array A is actually stored in the count of each color, and then we can then output each color backwards to get our sorted array.
Nine-chapter algorithm surface test 70 row Color II sort colors