算法学习

算法题--三颜色排序

2020-04-20  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note: You are not suppose to use the library's sort function for this problem.

Example:

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

Follow up:

A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?

2. 思路1:记录三个颜色的位置下标+从左到右遍历

即跟着white的视角来观察过程

3. 代码

# coding:utf8
from typing import List


class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        red, white, blue = 0, 0, len(nums) - 1
        while white <= blue:
            if nums[white] == 0:
                nums[red], nums[white] = nums[white], nums[red]
                red += 1
                white += 1
            elif nums[white] == 1:
                white += 1
            else:
                nums[white], nums[blue] = nums[blue], nums[white]
                blue -= 1


def my_test(solution, nums):
    print('input:{}'.format(nums))
    solution.sortColors(nums)
    print('output:{}'.format(nums))
    print('=' * 50)


solution = Solution()
my_test(solution, [2, 0, 2, 1, 1, 0])
my_test(solution, [0, 0, 1, 2, 1, 2])


输出结果

input:[2, 0, 2, 1, 1, 0]
output:[0, 0, 1, 1, 2, 2]
==================================================
input:[0, 0, 1, 2, 1, 2]
output:[0, 0, 1, 1, 2, 2]
==================================================

4. 结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读