4ms clear code O(n), extra three variable


  • 0
    A
    #include <vector>
    using namespace std;
    class Solution {
    public:
        void swap(int& a, int& b)
        {
            int tmp = a;
            a = b;
            b = tmp;
        }
    
        void sortColors(vector<int>& nums) {
            int begine = 0;
            int end = nums.size() - 1;
            for (int i = 0; i < nums.size(); ++i)
            {
                switch (nums[i])
                {
                case 0:
                    if (begine == i)
                    {
                        begine++;
                    }
                    else
                    {
                        swap(nums[i], nums[begine]);
                        i--;
                        begine++;
                    }
                    break;
                case 2:
                    if (end == i)
                    {
                        end--;
                    }
                    else
                    {
                        swap(nums[i], nums[end]);
                        i--;
                        end--;
                    }
                    break;
                default:
                    break;
                }
                if (i >= end)
                    break;
            }
        }
    };

Log in to reply
 

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