leetcode笔记:Sort Colors

一. 题目描写叙述

Given an array with n objects colored red, white or blue, sort them 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.

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 an one-pass algorithm using only constant space?

二. 题目分析

题目一開始说到一组对象,包括红白蓝三种颜色。然后要对他们进行排序,说白了就是对一个仅仅含有0, 1, 2三个数字的数组从小到大排序。

题目要求:come up with an one-pass algorithm using only constant space,因此仅仅能扫描一次。这里採取的方法是,统计0, 1, 2三个数字分别出现的次数。再将数组nums又一次构建为从0到2排列的数组,这样的方法没有使用数组元素间的交换,仅仅需扫描一次nums。

三. 演示样例代码

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    void sortColors(vector<int>& nums) 
    {
        int SIZE = nums.size();
        int count[3] = {0, 0, 0};
        for (int i = 0; i < SIZE; ++i)
            ++count[nums[i]];

        for (int i = 0, index = 0; i < 3; ++i)
            for (int j = 0; j < count[i]; ++j)
                nums[index++] = i;
    }
};

一个測试结果:

这里写图片描写叙述

四. 小结

本题的解法还是挺多的,可多參考网上的其它解法。

原文地址:https://www.cnblogs.com/cxchanpin/p/7018773.html