My C++ Solution,4 ms,Very easy to understand!


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.