LeetCode Sort Colors

Source: Internet
Author: User

LeetCode Sort Colors
LeetCode-solving Sort Colors

Original question

An array composed of three colors: red, white, and blue. The elements of the same color are put together in the red, white, and blue order. 0 indicates red, 1 indicates white, and 2 indicates blue. This is also known as the Dutch flag.

Note:

Traverse only once as much as possible

Example:

Input: nums = [1, 2, 1, 2, 0, 2, 1, 0, 2]

Output: [0, 0, 0, 0, 1, 1, 1, 2, 2, 2]

Solutions

If there are only two colors, it is easy to think of the first and last two pointers traversing the middle. If the color is incorrect, the positions are exchanged. Three colors can still be used to do this, but one more pointer is required. The first and second pointers are used to separate the arranged red and blue, and the middle pointer is used to traverse the elements:

If it is red, it will be exchanged with the front pointer, and the two will move to the back. The front pointer must be white, because the pointer has scanned those elements. If it is white, if it is blue, it is switched to the back pointer. The back pointer moves forward, and the middle pointer cannot move backward, because we are not sure what color the element is. AC source code
class Solution(object):    def sortColors(self, nums):        """        :type nums: List[int]        :rtype: void Do not return anything, modify nums in-place instead.        """        left = mid = 0        right = len(nums) - 1        while mid <= right:            if nums[mid] == 0:                nums[mid], nums[left] = nums[left], nums[mid]                left += 1                mid += 1            elif nums[mid] == 1:                mid += 1            else:                nums[mid], nums[right] = nums[right], nums[mid]                right -= 1if __name__ == "__main__":    l = [1, 2, 1, 2, 0, 2, 1, 0, 2, 0, 0, 2]    Solution().sortColors(l)    assert l == [0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2]

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.