Nine-chapter algorithm surface question 69 row color sort Colors

Source: Internet
Author: User
Nine chapters count judges Net-original website

http://www.jiuzhang.com/problem/70/

Topic

To an array, and the value of the elements inside the array is only likely to be 0,1,2, and then the array is now sorted.

Online test

http://www.lintcode.com/en/problem/sort-colors/

Answer

The method of one pass requires two pointer techniques. With two pointers, a pointer x pointing to the array header is the position of 0 and 1, the other pointer y points to the position where the tail represents the difference between 1 and 2, and then we iterate over the array, and if the element currently encountered is 0, then we swap it with the element where x points to the position, and X moves forward, updating the boundary; Then, if it is 2, then replace the element where Y points to, and y back one step, so that X is the position of 0 and 1, and y is the position of 1 and 2. This method of time complexity O (n), Spatial complexity O (1)

Nine-chapter algorithm surface question 69 row color 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.