My C++ solution, 4ms, counting sort


  • 1
    Z
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            vector<int> countArray(3,0);
            
            int n=nums.size();
            for(int i=0;i<n;i++)
            countArray[nums[i]]++;
            
            int count=0;
            for(int i=0;i<3;i++){
                for(int j=0;j<countArray[i];j++){
                    nums[count]=i;
                    count++;
                }
            }
        }
    };
    

    Obviously, this problem can be solved by using counting sort. I also tried using quick sort to solve it, and the elapsed time for quick sort is 8ms.


  • 0
    J

    During 3 different executions, my runtimes were 4ms, 6ms and 8ms respectively.
    So, in my opinion, this may not be trustworthy enough for inferences


Log in to reply
 

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