My one-pass algorithm using constant space


  • 0
    U
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            int i0, i2;
            i0 = 0;
            i2 = nums.size()-1;
            for (int i = 0; i < nums.size(); i++) {
                while (nums[i] == 2) {
                    swap(nums[i], nums[i2--]);
                    if (i2 <= i)
                        break;
                }
                if (nums[i] == 0)
                    swap(nums[i], nums[i0++]);
                if (i2 <= i)
                    break;
            }
            return;
        }
    };

Log in to reply
 

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