【C++】【LeetCode】75. Sort Colors

来源:互联网 发布:9377皇图进阶数据 编辑:程序博客网 时间:2024/05/20 14:43

题目

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.

思路

LeetCode的discuss里有一个很好的思路,效率不高,但是便于理解,记录在这里:链接

代码

class Solution {public:    void sortColors(vector<int>& nums) {        int r = 0;        int w = 0;        int b = nums.size() - 1;        while (w <= b) {            if (nums[w] == 2) {                int tmp = nums[w];                nums[w] = nums[b];                nums[b] = tmp;                b--;            } else if (nums[w] == 0) {                int tmp = nums[w];                nums[w] = nums[r];                nums[r] = tmp;                r++;                w++;            } else if (nums[w] == 1) {                w++;            }        }    }};
原创粉丝点击