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.this
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.code
Note:
You are not suppose to use the library's sort function for this problem.it
對0、一、2進行計數後再填充。io
class Solution {
public:function
// 好無聊:直接對0、一、2進行計數,而後填充 void sortColors(vector<int>& nums) { int cnt[3] = {0, 0, 0}; for (int i = 0; i < nums.size(); i++) { cnt[nums[i]]++; } cnt[1] += cnt[0]; for (int i = 0; i < nums.size(); i++) { if (i < cnt[0]) { nums[i] = 0; } else if (i < cnt[1]) { nums[i] = 1; } else { nums[i] = 2; } } }
};class