Sort Colors Leetcode #75 题解[C++]

题目来源


https://leetcode.com/problems/sort-colors/description/

题目描述


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?

给出只由三个元素(可重复出现)的数组{0,1,2}, 对它们进行排序.

解题思路


这题因为只有3个元素要排序, 所以我们可以采取一个类似”switch”的暴力排序法.

如果是0, 移到最前面.
如果是1, 不去理他.
如果是2, 移到最后面.

这里还有一个小tip, 怎么移也是一个值得注意的地方, 千万不要用insert之类的方法, 许多语言中用这种方法都耗时巨大, 而选择swap方法便往往只需交换一下指针, 可谓刷题卡时间之必备佳品.

代码实现


#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
    void sortColors(vector<int>& nums) {
        int last_unsorted = nums.size() - 1;
        int first_unsorted = 0;

        for(int i=0;i<=last_unsorted;i++){
            if(nums[i]==0) swap(nums[i],nums[first_unsorted++]);
            else if(nums[i]==2) swap(nums[i--],nums[last_unsorted--]);
    }
    }   
};

代码表现


第一个百人斩, 开心\ (/ω\)
75_ac

猜你喜欢

转载自blog.csdn.net/wayne_mai/article/details/80290540