# LeetCode 75. Sort Colors ## 題目 [LeetCode 75. Sort Colors](https://leetcode.com/problems/sort-colors/) > Given an array nums 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. > >We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively. > >You must solve this problem without using the library's sort function. ## 個人解題思路 #### 統計`nums`中`0`, `1`, `2` 的個別數量,最後再依序放入`nums`裡面。 ```cpp= class Solution { public: void sortColors(vector < int > & nums) { int cnt = 0, zero = 0, one = 0, two = 0; for (auto i = pp.begin(); i != pp.end(); i++) { if ( * i == 0) zero++; if ( * i == 1) one++; if ( * i == 2) two++; } if (zero) { cnt += zero; for (int i = 0; i < cnt; i++) { pp.at(i) = 0; } } if (one) { for (int i = cnt; i < (cnt + one); i++) { pp.at(i) = 1; } cnt += one; } if (two) { for (int i = cnt; i < (cnt + two); i++) { pp.at(i) = 2; } } } }; ``` ## 提交結果 ![](https://i.imgur.com/j8yQGyN.png) ###### tags: `LeetCode` `C++`