LeetCode

来源:互联网 发布:stm32f103rc数据手册 编辑:程序博客网 时间:2024/05/11 06:01

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.


有n个对象,值分别为0,1,2,现在希望对这n个对象进行排序,使得0在前,2在后。

嗯,循环交换。设立两个指针,一个指向开头,一个指向结尾,若是为0或是为2,即进行交换。时间复杂度O(n),空间复杂度O(1)

class Solution {public:    void sortColors(vector<int>& nums) {        if (nums.empty()) return;        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--]);            while (nums[i] == 0 && i > zero) swap(nums[i], nums[zero++]);        }        return;    }};


原创粉丝点击