Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/32/
TopicsThere are red, yellow and blue three-colored balls in a row, these balls are sorted, please use as little space and time.
Answer
Suppose the order is red Yellow blue. Iterate from the beginning with two pointers, stop when the first pointer encounters a non-red, and if the second pointer finds the first red stop after the first pointer, swap the color of the two pointer. Repeat the above procedure. Until the second pointer cannot find any red. At this point the first pointer is yellow or blue at the end. Continue to do the same with the yellow standard, and you can order the yellow and blue. In the process of traversal, the complexity is O (n) because the second pointer does not need to go back to the position of the first pointer each time.
Interviewer Angle
This topic is a survey of sorting algorithms. Obviously, job seekers can at least be able to answer an O (nlogn) sorting method. It is also possible to think of the O (n) method using the Count sort (since there are only three colors, count the number of each color). At this point the interviewer will ask that if the counting sort is not applied, can the efficiency of O (n) be obtained by simple comparison and exchange? Many job seekers will be blindfolded at this point, because they think the count is the best, and the interviewer must be embarrassing himself. In the process of the interview if this mentality (think the interviewer embarrassed himself) is very scary, the interviewer will never embarrass job seekers. The interviewer just wants to look at how active the job seeker is by setting different restrictions. Because in the actual project, in many cases, can not completely in the ideal external environment to consider the problem, need to consider many constraints at the same time, it is your ability to show, seize the interviewer "embarrassed" your opportunity to take off and get an offer.
Nine-chapter algorithm surface test 32 ball sorting