【LeetCode】90. Sort Colors

题目描述(Medium)

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.

题目链接

https://leetcode.com/problems/first-missing-positive/description/

Example 1:

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

算法分析

由于只有三种颜色,可以设置两个index,一个是red的index,一个是blue的index,两边往中间走。

提交代码:

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int red = 0, blue = nums.size() - 1;
        
        for (int i = 0; i < blue + 1; )
        {
            if (nums[i] == 0)
                swap(nums[i++], nums[red++]);
            else if (nums[i] == 2)
                swap(nums[i], nums[blue--]);
            else
                ++i;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82989148