c++ 3ms simple solution


  • 0

    class Solution {
    public:
    void sortColors(vector<int>& nums) {
    int head=0,tail=nums.size()-1;
    while(head!=tail){
    while(nums[head]==0&&head<tail){
    head++;
    }
    while(nums[tail]>0&&head<tail){
    tail--;
    }
    swap(nums[head],nums[tail]);
    }
    tail=nums.size()-1;
    while(head!=tail){
    while(nums[head]==1&&head<tail){
    head++;
    }
    while(nums[tail]==2&&head<tail){
    tail--;
    }
    swap(nums[head],nums[tail]);
    }
    }
    };


Log in to reply
 

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