【LeetCode】- Sort Colors(荷兰国企,颜色分类)

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、问题描述:

  • 数组排序,但是不能遍历统计0,1,2的个数,怎么做?

3、问题关键:

  • 可以遍历一次,遇到0放到最前面,遇到2放到最后面。

  • 双指针做法。

  • 遇到问题看看双指针行不行,双指针是一个非常有效而且常用的方法。

4、C++代码:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int zero = 0 , second = nums.size() - 1;//定义两个指针。
        for (int i = 0; i <= second; i ++) {
            while(nums[i] == 2 && i < second) swap(nums[i], nums[second --]);//将2放到末尾,直到当前位置不是2。可以自行思考一下为什么是这样的。
            if(nums[i] == 0) swap(nums[i], nums[zero ++]); //如果是0那么就放到最前面。
        }
    }
};
    原文作者:邓泽军_3679
    原文地址: https://www.jianshu.com/p/6be1e3fc4fa5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞