c++ O(n) solution in 1 paas


  • 0
    S
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            int len = nums.size();
            int count = 0;
            int i=-1,j=-1, k=len, index=0;
            for(;index<len && index<k;)
            {
                if(nums[index]==0)
                {
                    if(j>-1)
                    {
                        nums[j] = 0;
                        nums[index] = 1;
                        i = j;
                        j++;
                    }
                    else
                        i = index;
                    
                    index++;
                } else if(nums[index]==1)
                {
                    if(j==-1)
                        j = index;
                    
                    index++;
          
                } else if(nums[index]==2)
                {
                    k--;
                    nums[index] = nums[k];
                    nums[k] = 2;
                }
            }
        }
    };
    
    

Log in to reply
 

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