Nine-chapter algorithm surface test 70 row Color II sort colors

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.